组合数组数组的唯一项,同时对值求和 - JS / lodash



我有一个看起来像这样的数组:

currArray = 
[ 
['a', 2],
['b', 3],
['c', 5],
['a', 2],
['b', 4],
['d', 6]
]

我正在尝试组合在 [0] 处具有相同值的数组,同时在 [1] 处添加值。因此,输出如下所示:

newArray = 
[ 
['a', 4], 
['b', 7], 
['c', 5], 
['d', 6] 
]

目前正在通过Vanilla JavaScript和lodash尝试这个。

任何建议都非常感谢。

您可以使用Array.reduce()

const currArray = [
['a', 2],
['b', 3],
['c', 5],
['a', 2],
['b', 4],
['d', 6]
];
const result = currArray.reduce((res, [key, val]) => {
const correspondingArr = res.find(arr => arr[0] === key);
if (correspondingArr) {
correspondingArr[1] += val;
} else {
res.push([key, val]);
}
return res;
}, []);
console.log(result);

我们可以使用哈希图来存储总和,然后将哈希图映射到数组。

currArray = 
[ 
['a', 2],
['b', 3],
['c', 5],
['a', 2],
['b', 4],
['d', 6]
]
// create a hash map
const currArrInfo = {};
// fill the hash map
currArray.forEach((miniArray) => {
currArrInfo[miniArray[0]] = currArrInfo[miniArray[0]] || 0;
currArrInfo[miniArray[0]]+=currArrInfo[miniArray[1]];
});
// map the hash map to array
currArray = Object.keys(currArrInfo).map((key) => [key, currArrInfo[key]]);

您可以将_.groupBy()_.head()一起使用,以将所有条目分组为同一第一项。然后映射组,并对每个组的第二个元素求和(用_.sumBy()_.last()(:

const currArray = [["a",2],["b",3],["c",5],["a",2],["b",4],["d",6]]
const result = _.map(
_.groupBy(currArray, _.head), // group by the 1st item
(group, key) => [key, _.sumBy(group, _.last)] // take the key from each group, and sum all the 2nd items of each group
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

使用 lodash/fp,您可以使用_.flow()创建一个函数,该函数按第一个元素对项目进行分组,对每个组的第 2 个元素求和,然后转换为条目:

const { flow, groupBy, head, mapValues, sumBy, last, toPairs } = _
const fn = flow(
groupBy(head), // group by the 1st item
mapValues(sumBy(last)), // take the key from each group, and sum all the 2nd items of each group
toPairs // convert to entries
)
const currArray = [["a",2],["b",3],["c",5],["a",2],["b",4],["d",6]]
const result = fn(currArray)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

您可以使用 Map 为每个不同的currArray[0]保留运行计数:

currArray = 
[ 
['a', 2],
['b', 3],
['c', 5],
['a', 2],
['b', 4],
['d', 6]
];

let map = new Map();
currArray.forEach(function(subAry)
{
let runningTally = map.get(subAry[0]);
if (runningTally)
{
map.set(subAry[0],runningTally + subAry[1]);
}
else
{
map.set(subAry[0],subAry[1]);
}
});
let newArray = Array.from(map);
console.log(newArray);

最新更新