减少嵌套数组中的元素
Reduce elements in nested array
我正在尝试过滤数组并减少值,但我不知道如何操作。
所以,我有一个示例数组 [["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]
如何使用 return [["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]]
创建函数?
你有什么想法吗?
您可以使用 Array.prototype.reduce()
到 return 包含每个唯一名称及其值的对象。
最后使用 Object.entries()
从该对象中获取包含 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;
}, {});
我们需要一个数组来构造,同时我们减少另一个,如您在上面看到的。在每一步中,我们都会检查我们是否已经拥有该元素。如果没有,那么我们添加它。否则我们根据需要增加它。
我正在尝试过滤数组并减少值,但我不知道如何操作。
所以,我有一个示例数组 [["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]
如何使用 return [["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]]
创建函数?
你有什么想法吗?
您可以使用 Array.prototype.reduce()
到 return 包含每个唯一名称及其值的对象。
最后使用 Object.entries()
从该对象中获取包含 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;
}, {});
我们需要一个数组来构造,同时我们减少另一个,如您在上面看到的。在每一步中,我们都会检查我们是否已经拥有该元素。如果没有,那么我们添加它。否则我们根据需要增加它。