gpt4 book ai didi

javascript - 将二维数组与键值数组相结合

转载 作者:行者123 更新时间:2023-12-03 05:23:41 26 4
gpt4 key购买 nike

我有一个数组,其中每行都是一个具有 2 个值、S/N 和说明的数组。

 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);
};

最佳答案

这个怎么样。

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);
}

首先,你算的是一个对象,而不是一个数组。那么我们不需要 forEach

关于javascript - 将二维数组与键值数组相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com