gpt4 book ai didi

javascript - 如何通过两项条件找到对象内的最高值?

转载 作者:行者123 更新时间:2023-12-01 01:07:49 25 4
gpt4 key购买 nike

我正在尝试通过 IDdate 获取对象的最高值。为了更好地解释,这是我的数组:

[  
{
"id":"6",
"date":"201901",
"value":"1"
},
{
"id":"6",
"date":"201901",
"value":"12"
},
{
"id":"6",
"date":"201901",
"value":"123"
},
{
"id":"6",
"date":"201901",
"value":"1231"
},
{
"id":"6",
"date":"201902",
"value":"4"
},
{
"id":"6",
"date":"201902",
"value":"45"
},
{
"id":"5",
"date":"201902",
"value":"56"
},
{
"id":"5",
"date":"201902",
"value":"46"
}
]

我正在尝试获取此返回(按id日期过滤最高):

[  
{
"id":"6",
"date":"201901",
"value":"1231"
},
{
"id":"6",
"date":"201902",
"value":"45"
},
{
"id":"5",
"date":"201902",
"value":"56"
}
]

在我的代码中,我使用了 mapfilter 但不起作用:

let resultados = array

array.map(item => {
resultados.filter(itemFilter => {
if(item.id == itemFilter.id && item.date == itemFilter.date){
if(itemFilter.value > item.value){
return itemFilter.value
}
}
})
})

类似的解决方案是 this

有人可以帮助我吗?

最佳答案

您可以选择 Map使用所需键的组合键进行分组。然后取较大的值。

var data = [{ id: "6", date: "201901", value: "1" }, { id: "6", date: "201901", value: "12" }, { id: "6", date: "201901", value: "123" }, { id: "6", date: "201901", value: "1231" }, { id: "6", date: "201902", value: "4" }, { id: "6", date: "201902", value: "45" }, { id: "5", date: "201902", value: "56" }, { id: "5", date: "201902", value: "46" }],
result = Array.from(data
.reduce((m, o) => (key =>
!m.has(key) || m.get(key).value < o.value
? m.set(key, o)
: m
)(['id', 'date'].map(k => o[k]).join('|')), new Map)
.values()
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何通过两项条件找到对象内的最高值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55458323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com