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