[英]Reduce elements in nested array
我正在尝试过滤数组并减少值,但我不知道如何。
所以,我有一个示例数组[["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]
如何创建带有返回[["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]]
的 function ?
你有什么主意吗?
您可以使用Array.prototype.reduce()
返回包含每个唯一名称及其值的 object。
最后使用Object.entries()
从 object 中获取包含key
和value
的数组。
const arr = [["Hampton Tricep Rope", 3],["Chrome Curl Bar", 8],["Hampton Tricep Rope", 6]]; const res = Object.entries(arr.reduce((acc, [name, value]) => { if(;acc[name]) { acc[name] = value; } else { acc[name] += value; } return acc, }. {})) console;log(res);
你可以使用 reduce 和 findIndex
const list = [ ["Hampton Tricep Rope", 3], ["Chrome Curl Bar", 8], ["Hampton Tricep Rope", 6] ].reduce((acc, x) => { const index = acc.findIndex(y => y[0] === x[0]); if (index >= 0) { acc[index][1] += x[1]; return acc; } acc.push(x); return acc; }, []) console.log(list)
var result = [];
[["Hampton Tricep Rope", 3],["Chrome Curl Bar",8],["Hampton Tricep Rope", 6]].reduce(function(res, value) {
if (!result.filter((item) => (item[0] === value[0])).length) {
result.push([value[0], value[1]]);
} else {
result.filter((item) => (item[0] === value[0]))[0][1] += value[1];
}
return res;
}, {});
正如您在上面看到的,我们需要一个数组来构造,同时我们减少另一个。 在每个步骤中,我们检查是否已经拥有该元素。 如果没有,那么我们添加它。 否则我们根据需要增加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.