JavaScript 合并重复项并增加数组中每个对象的计数
问题陈述要求合并重复的元素,并增加数组中每个对象的计数,并在JavaScript中实现此程序。
理解问题
为了开始编码,我们需要了解JavaScript函数的基本功能。JavaScript中的预定义函数将完成我们任务的一半。合并和消除重复是可以执行的基本数组优化操作。在这个问题中,我们将定义一个计数变量,用于计算数组中有多少个条目。
我们将使用reduce()方法遍历数组中的每个项,以计数和减小数组的大小来移除重复项。因此,reduction方法从一个初始值开始,并使用回调函数累积值。
在我们的示例中,使用了具有水果和计数两个特性的不同水果。为了增加这个计数值,如果它们具有相同的水果值,我们将它们合并起来。
Input Array = [
{fruit: "Banana", count: 12},
{fruit: "Kiwi", count: 10},
{fruit: "Banana", count: 15},
{fruit: "Kiwi", count: 9},
]
o/p Array = [
{fruit: "Banana", count: 27},
{fruit: "Kiwi", count: 19},
]
步骤
以下是程序的算法:
步骤 1 :创建一个名为mergeAndCount的数组,用于存储合并的对象。这一步将初始化第一个操作以检查重复项。
步骤 2 :使用回调函数和一个空起始值,在水果数组([])上调用reduce方法。
步骤 3 :通过回调函数确定数组是否包含与c对象具有相同名称的对象:否则,将c项包含在数组中。如果是这样,将c对象的计数加到a中已有项的计数中。
步骤 4 :从第4步中的reduce函数中返回数组”a”。
步骤 5 :将mergeAndCount返回到控制台。
示例
// define a function to check power of 3
const fruits = [
{fruit: "Apple", count: 12},
{fruit: "Orange", count: 10},
{fruit: "Pineapple", count: 5},
{fruit: "Apple", count: 10},
{fruit: "Orange", count: 4},
{fruit: "Pineapple", count: 6},
{fruit: "Banana", count: 12},
{fruit: "Pineapple", count: 3}
]
const mergeAndCount = fruits.reduce((a, c) => {
const obj = a.find((obj) => obj.fruit === c.fruit);
if(!obj){
a.push(c);
}
else{
obj.count += c.count;
}
return a;
}, []);
console.log("After counting and merging:");
console.log(mergeAndCount);
输出
After counting and merging:
[
{ fruit: 'Apple', count: 22 },
{ fruit: 'Orange', count: 14 },
{ fruit: 'Pineapple', count: 14 },
{ fruit: 'Banana', count: 12 }
]
示例
// define an array
const data = [
{ name: 'apple', category: 'fruit' },
{ name: 'orange', category: 'fruit' },
{ name: 'banana', category: 'fruit' },
{ name: 'pear', category: 'fruit' },
{ name: 'apple', category: 'fruit' },
{ name: 'broccoli', category: 'vegetable' },
{ name: 'carrot', category: 'vegetable' },
{ name: 'spinach', category: 'vegetable' },
{ name: 'spinach', category: 'vegetable' },
{ name: 'spinach', category: 'vegetable' }
];
// create a function to merge and count
function mergeDuplicates(data, propToMerge) {
let counts = {};
for (let obj of data) {
let propValue = obj[propToMerge];
if (propValue in counts) {
counts[propValue]++;
} else {
counts[propValue] = 1;
counts[propValue + '_data'] = [obj];
}
}
let result = [];
for (let propValue in counts) {
if (counts[propValue] > 1 && propValue !== propValue +
'_data') {
result.push({ [propToMerge]: propValue, count: counts[propValue],
data: counts[propValue + '_data'] });
}
}
return result;
}
// call the mergeDuplicates
const result = mergeDuplicates(data, 'name');
console.log(result);
输出
[
{ name: 'apple', count: 2, data: [ [Object] ] },
{ name: 'spinach', count: 3, data: [ [Object] ] }
]
时间复杂度
上述代码的时间复杂度为O(n)。因为执行完成所需的时间与数组的长度相等。空间复杂度也为O(n),用来存储n个元素在数组中。
结论
这是解决这类问题的基本思路。在整个过程中,我们使用了一个名为mergeAndCount()的函数,算术运算符和比较运算符来解决问题。还学会了如何计算算法的时间和空间复杂度。