So I have data like this:
data = [
[{a: "b", value: 12}, {a: "bb", value: 39}, {a: "bb", value: 150}],
[{a: "c", value: 15}, {a: "cc", value: 83}, {a: "ccc", value: 12}],
[{a: "d", value: 55}, {a: "dd", value: 9}, {a: "dd", value: 1}]
]
I want to get max values of value in each array of objects. So the result should be like this:
maxValues = [150, 83, 55]
Right now my code is:
let maxValues = []
let tmp;
let highest = Number.NEGATIVE_INFINITY;
data.map((eachArr, index) => {
for(let i = eachArr.length -1; i >= 0; i--){
tmp = eachArr[i].value;
if(tmp > highest) highest = tmp;
}
maxValues.push(highest)
})
and the result is
maxValues = [150, 150, 150]
How can I achieve this?
You could use the spread syntax and take the max of mapped value
.
The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
var data = [[{ a: "b", value: 12}, {a: "bb", value: 39 }, {a: "bb", value: 150 }], [{ a: "c", value: 15}, {a: "cc", value: 83 }, {a: "ccc", value: 12 }], [{ a: "d", value: 55}, {a: "dd", value: 9 }, {a: "dd", value: 1 }]],
result = data.map(a => Math.max(...a.map(b => b.value)));
console.log(result);