gpt4 book ai didi

javascript - 如何根据 JavaScript 中的另一个数组比较和更新此数组?

转载 作者:行者123 更新时间:2023-12-02 14:41:02 24 4
gpt4 key购买 nike

我正在研究这个challenge—Inventory update ,在 Free CodeCamp.com 上挑战指出:

Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.

function updateInventory(arr1, arr2) {
for (var x = 0; x < arr1.length; x++) {

for (var y = 0; y < arr2.length; y++) {

if (arr1[x][1] === arr2[y][1]) {
arr1[x][0] = arr2[y][0] + arr1[x][0];
}
}
}

for(var j = 0; j < arr2.length; j++){

var i = arr2[j][1];

for(var k = 0; k < arr1.length; k++){
var idx = arr1.indexOf(i);
if(idx === -1){
arr1.push(i);
}
}


}
return arr1;

}

当我尝试时:

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], 
[1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"],
[3, "Half-Eaten Apple"], [67, "Bowling Ball"],
[7, "Toothpaste"]]).length // I get 8 instead of 6

当我尝试时:

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], 
[1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"],
[3, "Half-Eaten Apple"], [67, "Bowling Ball"],
[7, "Toothpaste"]])

我得到: enter image description here

什么时候我应该得到:

[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], 
[3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]

我相信这就是我的问题所在......

for(var j = 0; j < arr2.length; j++){

var i = arr2[j][1];

for(var k = 0; k < arr1.length; k++){
var idx = arr1.indexOf(i);
if(idx === -1){
arr1.push(i);
}
}


}

因为它有点起作用。但是任何人都可以帮助完成字母排序部分吗?提前致谢!

最佳答案

试试这个

function updateInventory(arr1, arr2) {
for (var x = 0; x < arr1.length; x++) {

for (var y = 0; y < arr2.length; y++) {

if (arr1[x][1] === arr2[y][1]) {
arr1[x][0] = arr2[y][0] + arr1[x][0];
}
}
}

for (var j = 0; j < arr2.length; j++) {

var i = arr2[j][1];
var found = 0;

for (var k = 0; k < arr1.length; k++) {
if (arr1[k][1] === arr2[j][1]){
found = 1;}
}
if (found == 0)
arr1.push(arr2[j]);
}
arr1.sort(compareSecondColumn);
return arr1;

}

用于排序

function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}

关于javascript - 如何根据 JavaScript 中的另一个数组比较和更新此数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015898/

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