Reputation: 69
I have an array with multiple arrays of objects and Im trying to find the object with the highest value.
values = [
[ {_: "NAN", id: 1},
{_: "NAN", id: 2},
{_: "NAN", id: 3}
],
[{_: "3.006", id: 4},
{_: "7.206", id: 5},
{_: "1.906", id: 6}
],
[{_: "3.226", id: 7},
{_: "2.222", id: 8}
{_: "2.224", id: 9}
],
[{_: "0.006", id: 10},
{_: "0.321", id: 11},
{_: "0.938", id: 12}
]]
i tried to use .map and .find
var a = Math.max(...values.map(e => e._))
const highestPoint = values.find(values => values._ === a)
But its only bringing back NAN as highest point const highestPoint = {_: "NAN", id: 1}
, like its only looking through the first array?
Upvotes: 2
Views: 767
Reputation: 8135
Simple and fast enough:
const max = (arr = []) => {
return arr.reduce(
(m, i) => {
i.forEach((x) => {
if (x._ !== 'NAN' && m._ < x._) {
m = x;
}
});
return m;
},
{ _: -Infinity }
);
};
const max = (arr = []) => {
return arr.reduce(
(m, i) => {
i.forEach((x) => {
if (x._ !== 'NAN' && m._ < x._) {
m = x;
}
});
return m;
},
{ _: -Infinity }
);
};
const data = [
[
{ _: "NAN", id: 1 },
{ _: "NAN", id: 2 },
{ _: "NAN", id: 3 },
],
[
{ _: "3.006", id: 4 },
{ _: "7.206", id: 5 },
{ _: "1.906", id: 6 },
],
[
{ _: "3.226", id: 7 },
{ _: "2.222", id: 8 },
{ _: "2.224", id: 9 },
],
[
{ _: "0.006", id: 10 },
{ _: "0.321", id: 11 },
{ _: "0.938", id: 12 },
],
];
console.log(max(data));
Upvotes: 0
Reputation: 386868
You could flat the arrays and take a filter with isFinite
and reduce the array.
var values = [[{ _: "NAN", id: 1 }, { _: "NAN", id: 2 }, { _: "NAN", id: 3 }], [{ _: "3.006", id: 4 }, { _: "7.206", id: 5 }, { _: "1.906", id: 6 } ], [{ _: "3.226", id: 7 }, { _: "2.222", id: 8 }, { _: "2.224", id: 9 }], [{ _: "0.006", id: 10 }, { _: "0.321", id: 11 }, { _: "0.938", id: 12 }]],
highest = values
.flat()
.filter(({ _ }) => isFinite(_))
.reduce((a, b) => +a._ > +b._ ? a : b);
console.log(highest);
Upvotes: 3
Reputation: 14211
When any of the arguments to Math.max
is not a number the result will be NaN
.
You have an array of arrays, so when mapping you get arrays as the argument to Math.max
so you need to filter the data and then pass it to max.
Something like this should work
values.flat().filter(item => !isNaN(Number(item._)))
Then you can pass this to max
and will work.
Upvotes: 0
Reputation: 12208
You can do this with Array.flatMap()
and Array.map()
to put all the objects into one array, Array.filter()
to remove the objects with "NAN", then Array.reduce
to find the highest number:
let vals=[[{_:"NAN",id:1},{_:"NAN",id:2},{_:"NAN",id:3}],[{_:"3.006",id:4},{_:"7.206",id:5},{_:"1.906",id:6}],[{_:"3.226",id:7},{_:"2.222",id:8},{_:"2.224",id:9}],[{_:"0.006",id:10},{_:"0.321",id:11},{_:"0.938",id:12}]];
let res = vals.flatMap(arr => {
return arr.map(obj => obj)
}).filter(obj => obj._ != "NAN").reduce((prv,cur) => prv._ > cur._ ? prv : cur)
console.log(res)
Upvotes: 0