我有这个数组
const products = [
["orange", 1],
["apple", 2],
["apple", 1],
["lemon", 1],
["lemon", -1],
];
我想得到这个结果:
newArray = [
["orange", 1],
["apple", 3],
["lemon", 0],
];
因此,它找到数组之间的重复值,然后对重复值的第二个元素求和。
到目前为止,我已经写了这个:
const fruits = [];
const quantity = [];
const newArray = [];
products.forEach((fruit) => {
fruits.push(fruit[0]);
quantity.push(fruit[1]);
});
fruits.filter((item, index) => {
if (fruits.indexOf(item) !== index) {
const value = quantity[index] + quantity[index - 1];
newArray.push([item, value]);
}
});
然后我进入控制台
console.log(newArray);
// [ [ 'apple', 3 ], [ 'lemon', 0 ] ]
这是正确的,但我错过了:
[范围],1]
找不到解决问题的方法,或者编写较少的代码来查找结果。
分组到一个对象中,其中水果名称是一个键,值是迄今为止找到的水果的总和,然后将其返回到数组中。
const products = [
["orange", 1],
["apple", 2],
["apple", 1],
["lemon", 1],
["lemon", -1],
];
const grouped = {};
for (const [fruit, quantity] of products) {
grouped[fruit] = (grouped[fruit] ?? 0) + quantity;
}
const result = Object.entries(grouped);
console.log(result);
另一种选择是使用reduce((函数
const products = [
["orange", 1],
["apple", 2],
["apple", 1],
["lemon", 1],
["lemon", -1],
];
const result = products.reduce((acc,val) => {
let obj = acc.find(a => a[0] == val[0])
if(!!obj){
obj[1] += val[1]
}else{
acc.push(val)
}
return acc
},[])
console.log(result)
const products = [
["orange", 1],
["apple", 2],
["apple", 1],
["lemon", 1],
["lemon", -1],
];
const flatten = products.flatMap(item => item);
const object = {}
for (let index = 0; index < flatten.length; index++) {
if ( index % 2 === 0){
const element = flatten[index];
const quantity = flatten[index + 1];
if(object[element]){
object[element] = object[element] + quantity
} else {
object[element] = quantity
}
}
}
const newArray = []
Object.entries(object).forEach(([fruit,quantity]) => {
newArray.push(`['${fruit}',${quantity}]`)
})
console.log(newArray); // ["['orange',1]", "['apple',3]", "['lemon',0]"]