Use Lodash's reduce to sum a collection - lodash

I have a simple collection:
[{a: 1}, {a: 2}, {a: 3}]
How do I use Lodash's reduce to get the sum of all "a" attributes?
This seems like a trivial / canonical use, but I can't get the syntax right and surprisingly can't find any docs beyond Lodash's example.
Using Lodash's docs example, it should be:
const total = _.reduce([{ a: 1}, {a: 2}, {a: 3}], (sum, elem) => elem.a);
However this returns the value "3" instead of "6'.
Note: I'm specifically asking about the usage of reduce. I'm aware of other methods like the one in this question.

You're forgetting to add sum to elem.a. Also, you need an initial reduction, otherwise, sum will be initialized to { a: 1 }:
_.reduce([{ a: 1}, {a: 2}, {a: 3}], (sum, elem) => sum + elem.a, 0);
You might want to look at sumBy() for this too. It's the same reducer, only more concise:
_.sumBy([{ a: 1}, {a: 2}, {a: 3}], 'a');

Related

ramda merging 2 json objects depending on there types

I need to merge 2 json object when the values are arrays there contents should be concatenated and if the values are primitive type then the value of first object should be taken.
R.mergeDeepWith(R.concat,
{ a: true, c: { values: [10, 20], d: { names: ['Alex']} }},
{ a: false, b: true, c: { values: [15, 35] , d: { address: ['Diesel Str 2']}}});
Arrays or deep object are working but for the key a I am getting an error.
I would probably do something like this:
const myMerge = mergeDeepWith(
(a, b) => is (Array) (a) && is (Array) (b) ? concat (a, b) : a)
console .log (myMerge (
{a: true, c: {values: [10, 20]}},
{a: false, b: true, c: {values: [15, 35]}}
))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script>const {mergeDeepWith, is, concat} = R</script>
We use mergeDeepWith and then call concat if both arguments are arrays, choosing the first one if not.

Divide list into parts

Is there a simple way to divide list into parts (maybe some lambda) in Kotlin?
For example:
[1, 2, 3, 4, 5, 6] => [[1, 2], [3, 4], [5, 6]]
Since Kotlin 1.2 you can use Iterable<T>.chunked(size: Int): List<List<T>> function from stdlib (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html).
Given the list: val list = listOf(1, 2, 3, 4, 5, 6) you can use groupBy:
list.groupBy { (it + 1) / 2 }.map { it.value }
Or if your values are not numbers you can first assign an index to them:
list.withIndex()
.groupBy { it.index / 2 }
.map { it.value.map { it.value } }
Or if you'd like to save some allocations you can go a bit more manual way with foldIndexed:
list.foldIndexed(ArrayList<ArrayList<Int>>(list.size / 2)) { index, acc, item ->
if (index % 2 == 0) {
acc.add(ArrayList(2))
}
acc.last().add(item)
acc
}
The better answer is actually the one authored by VasyaFromRussia.
If you use groupBy, you will have to add and index and then post-process extracting the value from an IndexedValue object.
If you use chunked, you simply need to write:
val list = listOf(10, 2, 3, 4, 5, 6)
val chunked = list.chunked(2)
println(chunked)
This prints out:
[[10, 2], [3, 4], [5, 6]]
Nice way of dividing list is by the use of function partition. Unlike groupBy it doesn't divide list by keys but rather by predicate which gives out Pair<List, List> as a result.
Here's an example:
val (favorited, rest) = posts.partition { post ->
post.isFavorited()
}
favoritedList.addAll(favorited)
postsList.addAll(rest)
The API says there is a GroupBy function, which should do what you want.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html
Or use sublist and break it up yourself
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/sub-list.html
If you want to divide a list into N parts.
(and not divide a list into parts of size N)
You can still use the chunked answer:
https://stackoverflow.com/a/48400664/413127
Only, first you need to find your chunk size.
val parts = 2
val list = listOf(10, 2, 3, 4, 5, 6)
val remainder = list.size % 2 // 1 or 0
val chunkSize = (list.size / parts) + remainder
val chunked = list.chunked(chunkSize)
println(chunked)
This prints out
[[10, 2, 3], [4, 5, 6]]
or when
val parts = 3
This prints out
[[10, 2], [3, 4], [5, 6]]
Interesting answer in Python here: Splitting a list into N parts of approximately equal length

bug or i don't understand "evolve"

When using Ramda.remove() by itself the function takes an array and outputs an array:
const grid = {rows: [1, 2, 3]};
R.remove(1, 1, grid.rows) // output: [1,3]
When I use Ramda.remove() as a transformation function in Ramda.evolve() it becomes an object {"0": 1, "1": 2, "2": 3} instead of an array [1,3]:
const grid = {rows: [1, 2, 3]};
R.evolve({
rows: R.remove(1, 1, grid.rows)
})(grid); // output:{"rows": {"0": 1, "1": 2, "2": 3}}
Do I understand evolve correctly or is a bug?
I imagine what you most likely want is
rows: R.remove(1, 1)
That will give you a function from a list to a shortened version of that list.
Just when writing this issue I realized what's wrong. I had to wrap R.remove in a function or bind the args. Basically, I needed to pass the reference to the function.
rows: () => R.remove(1, 1, grid.rows)

Mathematica Manipulate & PopupMenu

I'm new here and I've one question about the Manipulate function i Mathematica: I need to plot some data of a nested list where the first coordinate selects a category (of stocks, like banks, automobiles, pharmaceuticals, ...) and inside every category there are years and months coordinates, so it should be something like
In:= list[[cat]][[yr]][[mnth]]
Out= {1,2,3,4,5,6}
which are sorted stock prices belonging to category cat.
Now I'd like to plot this with an dynamic index in Manipulate with a PopupMenu which allows to select the category i need to plot: I already have a vector sect which at position cat has the sector referring to cat in list (which is to say sect[[i]] is the category of list[[i]]), but results are poor.
I've tried to use Manipulate[...,{index,sect}] and it seems to be the right way since there actually is a popup menu in the output, but it still gives error about syntax in the control cycle I need to plot only the right sector, something like
If[ sect[[j]] == index, Plot[ list[[j]] ] ].
So I'm stuck here, thanks to anyone will help!
I'm not convinced your data structure is optimal, but here's a sample set of data:
data2 = {
{"stock",
{
Range[6], Range[6, 12],
Range[12, 18]
},
{
Range[18, 24], Range[24, 30],
Range[30, 36]
}
},
{"bank",
Table[Range[i, i + 5], {i, 1, 18, 6}],
Table[Range[i, i + 5], {i, 18, 30, 6}]
}
};
and the Manipulate:
Manipulate[ListPlot[data2[[cat, year, month]]],
{{cat, 1, "Category"}, {1 -> "stock", 2 -> "bank"},
ControlType -> PopupMenu},
{{year, 2, "Year"}, {2 -> "2010", 3 -> "2011"},
ControlType -> PopupMenu},
{{month, 1, "Month"}, {1 -> "Jan", 2 -> "Feb", 3 -> "Mar"},
ControlType -> PopupMenu}]

Can we decrease Bar size width in BarChart in Mathematica?

dalist = {901, 503, 522, 1305}
cogColors = {RGBColor[0, 0, 1], RGBColor[1, 0, 0], RGBColor[0, 1, 0], RGBColor[1, 1, 0]}
BarChart[dalist, ChartStyle -> cogColors]
Is it possible to decrease the Bars Width ?
I may be missing the point, but cannot you merely change the aspect ratio?
BarChart[dalist, ChartStyle -> cogColors, AspectRatio -> 3, ImageSize -> 120]
BarChart is not intended to do that. You can only change the spacings.
Use RectangleChart instead if you need finer control:
RectangleChart[{{{1, 1}, {1, 1}, {1, 1}}, {{2, 2}, {2, 2}, {2, 2}}}]
Rather than changing the bar chart width, you can increase the bar spacing.
BarChart[dalist, ChartStyle -> cogColors, BarSpacing -> 1]
See Heike's answer to my earlier question. You need to use RectangleChart. If you want to keep a constant distance between bar centres, so that the bar-plus-spacing takes up a constant space, you can use the ChartElementFunction option together with an auxiliary function, as shown in Heike's answer. (This might also do what you want using BarChart, but I'd still recommend RectangleChart.)