[英]Javascript - find highest value in an object of arrays of objects
[英]Return object with highest value from multiple arrays of objects
我有一個包含多個 arrays 對象的數組,我試圖找到具有最高值的 object。
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}
]]
我嘗試使用.map 和.find
var a = Math.max(...values.map(e => e._))
const highestPoint = values.find(values => values._ === a)
但它只是將 NAN 帶回最高點const highestPoint = {_: "NAN", id: 1}
,就像它只查看第一個數組一樣?
您可以放平 arrays 並使用isFinite
進行過濾並減少數組。
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);
您可以使用Array.flatMap()
和Array.map()
將所有對象放入一個數組中, Array.filter()
刪除帶有“NAN”的對象,然后使用Array.reduce
找到最大的數字:
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)
當 arguments 到Math.max
中的任何一個不是數字時,結果將為NaN
。
你有一個 arrays 的數組,所以映射時你得到 arrays 作為Math.max
的參數,所以你需要過濾數據然后將它傳遞給 max。
這樣的事情應該工作
values.flat().filter(item =>.isNaN(Number(item._)))
然后你可以將它傳遞給max
並且會工作。
足夠簡單和快速:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.