gpt4 book ai didi

JavaScript:如何根据字段对数组中的相同字段进行添加和排序?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:39:50 25 4
gpt4 key购买 nike

我有以下数组 a,如下所示:

var a = [
{name: 'phone' , id:1 ,num:1},
{name: 'milk' ,id:2, num:1},
{name: 'apple' , id:3 , num:1},
{name: 'phone', id: 4, num:3},
]

我想按数组名过滤并添加自己的num

var currentName = a[0]
let newArrys=[]
for(let i = 0; i<a.length;i++){
if(currentName.name == a[i].name){
a[i].num = a[i].num + currentName.num
let tmepArry = [];
tempArry.push(a[i]);
newArrys.push(tempArry);
}
}

我正在尝试获取以下二维数组:

[
[{name: 'phone', id:1, num:4}],
[{name: 'milk',id:2, num:1}],
[{name: 'apple', id: 3 num:1}]
]

无法筛选出结果

我的尝试无效。

你能帮帮我吗?

最佳答案

给定:

var a = [
{name: 'phone' , id:1 ,num:1},
{name: 'milk' ,id:2, num:1},
{name: 'apple' , id:3 , num:1},
{name: 'phone', id: 4, num:3},
]
const newArrys = a.reduce((acc, current) => {
// find an object in the array with a matching name
const existing = acc.find(obj => obj.name === current.name);
if (existing) {
// combine the numbers
existing.num += current.num;
} else {
acc.push(current);
}
return acc;
}, []).map(obj => [obj])

这将为您提供所需的东西。

关于JavaScript:如何根据字段对数组中的相同字段进行添加和排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367891/

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