我有一个数组,其中每一行都是一个包含2个值的数组,S / N和Description。
array1 = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
正如您所看到的那样,有重复的内容。所以我编写的代码创建了一个count
数组,该数组包含键值对并计算每个项目。计数长度为1。
count = [xx1: 1
xx9: 3]
所以现在我想将两个数组合并为一个包含数量的新数组,在本例中最终输出如下所示。请注意,我还必须删除array1中的重复项。订单并不重要。
final_array = [["1","xx1","Small Car"],["3",xx9","Big Car"]];
到目前为止,这是我的JS代码,但基本上 .forEach 循环不会对count
数组起作用。任何人都可以帮助我,以便此代码适用于键值数组。
JS / Jquery的:
//Pull the Cart Data & Orangize
var savedList = JSON.parse(localStorage.getItem("partList"));
console.log(savedList);
determineQuantity(savedList); //Count quantity of each item
//Count the Quantity of each item in saved list & create key-value pairs
function determineQuantity(savedList){
var newList = [];
var count = [];
for (var i=0, j = savedList.length; i<j; i++){
count[savedList[i][0]] = (count[savedList[i][0]] || 0) + 1;
};
console.log(count);
//Combine Quantity Array with SavedList Array
count.forEach(function(item,index){
console.log("index = " + index + " item = " + item);
savedList.forEach(function(row){
if ($.inArray(item,row == 0)){ //if found in this row at index 0
var new_part = [count[index],row[0],row[1]];
console.log("new_part = " + new_part);
newList.push(new_part);
};
});
});
console.log(newList);
};
答案 0 :(得分:1)
var test = function(){
var array = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
var count = {xx1: 1, xx9: 3};
var map = {};
array.forEach(function(item){map[item[0]] = item[1]});
var newArray = [];
for(var key in count){
if(!map[key])
continue;
newArray.push([count[key], key, map[key]]);
}
console.log(newArray);
}
首先,你算是一个对象,而不是一个数组。然后我们不需要每个