Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  21] [ 7]  / answers: 1 / hits: 10438  / 5 Years ago, thu, october 17, 2019, 12:00:00

I have an array of objects having a boolean field X. [{..., x: true, y: 3, ...]



I need to aggregate this array, in order to obtain a value, true(or false), if all values of x are correspondingly true(or false), otherwise undefined... and a sum of y's...



is that possible to use the reduce Array function, groupby by underscorejs, or another one for this purpose?



ex:



[
{a:'titi', x: true, y: 3},
{a:'toto', x: false, y: 6}
]


result



       {x: undefined, y: 9}

More From » arrays

 Answers
4

this is pretty straight-forward with reduce:



.reduce((a, b) => ({
x: a.x == b.x ? a.x : undefined,
y: a.y + b.y
}))


Live example:





var input = [
{a:'titi', x: true, y: 3},
{a:'toto', x: false, y: 6}
];

console.log(input.reduce((a, b) => ({
x: a.x == b.x ? a.x : undefined,
y: a.y + b.y
})));




[#5898] Tuesday, October 15, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daren

Total Points: 577
Total Questions: 114
Total Answers: 120

Location: Malaysia
Member since Fri, Dec 3, 2021
3 Years ago
;