2 回答
TA贡献1111条经验 获得超0个赞
你可以使用reduce方法来做到这一点,
const data = [
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
]
const res = data.reduce((prev, curr) => {
const index = prev.findIndex((item) => item.id === curr.id && item.name === curr.name);
if(index > -1) {
const obj = prev[index];
if(obj.value < curr.value) {
prev[index] = {...obj, value: curr.value};
return prev;
}
}
prev.push(curr);
return prev;
}, []);
console.log(res);
TA贡献1876条经验 获得超7个赞
Reduce用于从数组中的所有项返回一个新值,该值基本上是累加器(与先前的值相加)。在这里我们可以使用它使用特定键对项目进行分组。正如您所写,您希望项目显示具有相同 id 和名称的最大值的记录,这些值可以作为键(让我们将它们视为该对象的复合私钥)。
在每次迭代中,我们检查是否已经有一个带有该键的对象添加到列表中,如果没有,我们添加我们现在所在的对象(在迭代期间),或者如果它的值小于我们当前所在的对象。如果该值较小,我们将使用当前对象覆盖该对象。
最后,我们使用 JS Object.values方法去除键并仅返回对象的值。
const list = [
{value: 1, id: 1, name: "x"},
{value: 5, id: 1, name: "x"},
{value: 1, id: 1, name: "y"},
{value: 8, id: 1, name: "y"},
{value: 1, id: 2, name: "x"},
{value: 3, id: 2, name: "x"},
{value: 1, id: 2, name: "y"},
{value: 4, id: 2, name: "y"}
];
const groupedResults = list.reduce((result, currentObject) => {
const currentKey = currentObject.id + currentObject.name;
if (!result[currentKey] || result[currentKey].value < currentObject.value) { /* Here we check if object with certain key was assigned to previously or if it was is the value smaller than of the object that we are currently seeing */
result[currentKey] = Object.assign({}, currentObject) //We need to do copy of the object (it can be also done using object destructuring) in order to have a new object that will not be bound by reference with the original one
};
return result;
}, {});
const requestedList = Object.values(groupedResults);
console.log(requestedList)
添加回答
举报