我正在處理一個對象數組。每個對象都有兩個屬性,大小和數量。Javascript:比較數組元素的屬性,如果相同,組合
var drives = [
{size:"900GB", count:3},
{size:"900GB", count:100},
{size:"1200GB", count:5},
{size:"900GB", count:1}
]
我不喜歡相同的大小如何產生多次,並想將所有重複的大小成僅有1數組索引。
首先我有按大小排序的數組。然後我試着做一個for-loop來管理重複。
drives.sort(function(obj1, obj2) {
var First = parseInt(obj1.size)
var Second = parseInt(obj2.size)
// Ascending: first size less than the previous
return First - Second;
})
for(var i = 0; i < drives.length-1; i++)
{
if(drives[i].size == drives[i+1].size)
{
drives[i+1].count+=drives[i].count;
//add the count of the first index to the second index's count
drives.splice(i, 1);
//delete the first index
}
}
https://jsbin.com/zayofiqoke/edit?js,console
的環路,似乎並不正確地迭代。它只結合了兩個索引。我如何實現我在找的東西?謝謝!
偉大的編輯旋轉! – wajeezy