lodash是一个JavaScript实用工具库,提供了很多函数用于简化常见的编程任务。使用lodash可以方便地合并两个数组和重复对象的求和值。
合并两个数组的方法有很多种,lodash提供了concat
函数和union
函数。
concat
函数:concat
函数会将两个数组合并成一个新数组,不去重。const _ = require('lodash');
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = _.concat(array1, array2);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
union
函数:union
函数会将两个数组合并成一个新数组,并去除重复元素。const _ = require('lodash');
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const mergedArray = _.union(array1, array2);
console.log(mergedArray); // [1, 2, 3, 4, 5]
对于重复对象的求和值,可以使用lodash提供的groupBy
函数和sumBy
函数。
groupBy
函数将重复的对象分组:const _ = require('lodash');
const array = [
{ id: 1, value: 10 },
{ id: 2, value: 20 },
{ id: 1, value: 30 },
];
const groupedObject = _.groupBy(array, 'id');
console.log(groupedObject);
/*
{
1: [
{ id: 1, value: 10 },
{ id: 1, value: 30 },
],
2: [
{ id: 2, value: 20 },
],
}
*/
sumBy
函数对分组后的对象进行求和值计算:const _ = require('lodash');
const array = [
{ id: 1, value: 10 },
{ id: 2, value: 20 },
{ id: 1, value: 30 },
];
const groupedObject = _.groupBy(array, 'id');
const sumByValue = _.mapValues(groupedObject, objects =>
_.sumBy(objects, 'value')
);
console.log(sumByValue); // { 1: 40, 2: 20 }
综上所述,使用lodash合并两个数组和重复对象的求和值可以通过concat
函数、union
函数、groupBy
函数和sumBy
函数来实现。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云