JavaScript数组中合并重复对象并增加计数
题目要求合并重复元素,并为数组中存在的每个对象增加计数,并用javascript实现该程序。
理解问题
为了开始编码,我们需要理解JavaScript函数的基本功能。JavaScript中的预定义函数将完成我们任务的一半。合并和消除重复项是可以在数组上执行的基本数组优化操作。在这个问题中,我们将定义一个计数变量,它将计算数组中有多少个条目。
我们将使用reduce()方法遍历数组中的每个项目,以计算并通过删除重复项来减小数组的大小。因此,reduce方法从一个初始值开始,并使用回调函数来累积值。
在我们的示例中,使用了具有水果和计数这两个属性的各种水果。为了增加这里的计数值,如果它们具有相同的水果值,我们将合并它们。
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项目包含在a数组中。如果是,则将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()的函数、算术运算符和比较运算符来解决问题。并了解如何计算算法的时间和空间复杂度。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP