我正在处理一个对象数组。每个对象都有两个属性,大小和数量。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