我一直想要这个,但对我来说还是很难的。
数据:
let data = [
[1, "Item A", "Food", 10],
[2, "Item B", "Food", 5],
[3, "Item C", "Food", 30],
[4, "Item A", "Hygiene", 30],
[4, "Item A", "Hygiene", 50],
[6, "Item D", "Food", 7],
[3, "Item C", "Food", 8],
[1, "Item A", "Food", 60],
]结果
let result = [
[1, "Item A", "Food", 70],
[2, "Item B", "Food", 5],
[3, "Item C", "Food", 38],
[4, "Item A", "Hygiene", 80],
[6, "Item D", "Food", 7],
]这是我认为应该采用的基本reduce(),但是如何设置标准e生成唯一的行呢?
const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);感谢你的帮助!
发布于 2022-06-24 20:01:11
您可以使用组合键进行分组。
const
data = [[1, "Item A", "Food", 10], [2, "Item B", "Food", 5], [3, "Item C", "Food", 30], [4, "Item A", "Hygiene", 30], [4, "Item A", "Hygiene", 50], [6, "Item D", "Food", 7], [3, "Item C", "Food", 8], [1, "Item A", "Food", 60]],
result = Object.values(data.reduce((r, a) => {
const key = [0, 1].map(i => a[i]).join('|');
if (r[key]) r[key][3] += a[3];
else r[key] = [...a];
return r;
}, {}));
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2022-06-24 20:28:44
我用过map和findIndex
我还使用了reverse()、Object.values和Object.fromEntries方法来获得唯一的方法:
let data = [
[1, "Item A", "Food", 10],
[2, "Item B", "Food", 5],
[3, "Item C", "Food", 30],
[4, "Item A", "Hygiene", 30],
[4, "Item A", "Hygiene", 50],
[6, "Item D", "Food", 7],
[3, "Item C", "Food", 8],
[1, "Item A", "Food", 60],
]
let objs = data.slice(); //in order to not mutate the source array data
let sumObjs = objs.map((curr, i) => {
let indexPrev = objs.findIndex(
(item) => item[1] == curr[1] && item[2] == curr[2]
);
if (indexPrev != -1 && i != indexPrev) {
//i != indexPrev to not accumelate the current one
//indexPrev =! -1 means that one is exist
objs[indexPrev][3] += curr[3];
}
return curr;
});
let result = Object.values(
Object.fromEntries(
sumObjs.reverse().map((obj) => [JSON.stringify(obj[1]+obj[2]), obj])
)
);
console.log(result);
https://stackoverflow.com/questions/72748799
复制相似问题