假设我们有一个像这样的数组的数组-
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
我们应该编写一个接受一个这样的数组的函数。请注意,所有子数组中都恰好包含三个元素。
我们的函数应该过滤掉具有重复值作为其第一个元素的子数组。此外,对于子数组,我们将其第三个元素添加到其现有的非重复副本中。
因此,对于上述数组,输出应类似于-
const output = [[12345, "product", "25"],[1234567, "other", "10"]];
为此的代码将是-
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]]; const addSimilar = (arr = []) => { const res = []; const map = {}; arr.forEach(el => { const [id, name, amount] = el; if(map.hasOwnProperty(id)){ const newAmount = +amount + +res[map[id] - 1][2]; res[map[id] - 1][2] = '' + newAmount; }else{ map[id] = res.push(el); } }); return res; } console.log(addSimilar(arr));
输出结果
控制台中的输出将是-
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]