4 回答

TA貢獻2051條經驗 獲得超10個贊
在對字符串值進行排序時,應使用該方法。localeCompare
function updateInventory (arr1, arr2) {
let invObj = {};
let updateObj = {};
let result = [];
arr1.forEach(x => invObj[x[1]] = x[0]);
arr2.forEach(x => updateObj[x[1]] = x[0]);
for (let key in updateObj) {
if (invObj[key]) {
invObj[key] += updateObj[key];
} else {
invObj[key] = updateObj[key];
}
}
result = Object.keys(invObj)
.sort((a, b) => a.localeCompare(b))
.map(key => [invObj[key], key]);
return result;
}
var curInv = [
[21, 'Bowling Ball'],
[2, 'Dirty Sock'],
[1, 'Hair Pin'],
[5, 'Microphone']
];
var newInv = [
[2, 'Hair Pin'],
[3, 'Half-Eaten Apple'],
[67, 'Bowling Ball'],
[7, 'Toothpaste']
];
console.log(
updateInventory(curInv, newInv)
);

TA貢獻1875條經驗 獲得超3個贊
您是否希望數組與第一個實例中的數據格式相同?
function updateInventory(arr1, arr2) {
let invObj = {}
let updateObj = {}
let result = []
arr1.forEach( x => invObj[x[1]] = x[0])
arr2.forEach( x => updateObj[x[1]] = x[0])
for(let key in updateObj) {
if (invObj[key]) {
invObj[key] += updateObj[key]
} else {
invObj[key] = updateObj[key]
}
}
return invObj;
}
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
console.log(updateInventory(curInv, newInv));

TA貢獻1909條經驗 獲得超7個贊
我會創建一個查找對象并保留對數組項的引用。在循環訪問當前項目后,我將循環訪問新項目。檢查它是否存在并更新計數。如果不存在,則將物料添加到庫存中。
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
// make a look up object to reference by the key
var lookup = curInv.reduce( (obj, item) => ({ ...obj, [item[1]]: item }), {})
// loop over the new inventory and add it on
newInv.forEach((item) => {
// check to see if we have the item
var key = item[1]
var exisiting = lookup[key]
// if exists add it
if (exisiting) {
exisiting[0] += item[0]
} else {
// new item
// add to our look up table in case it repeats
lookup[key] = item
// add it to the inventory list
curInv.push(item)
}
})
console.log(curInv)

TA貢獻1796條經驗 獲得超10個贊
對字符串進行排序時,它有點復雜,因為您還必須考慮大小寫。這是我在js中制作的表格中的一個片段,希望它有所幫助。您也可以像 taplar 所說的那樣使用 localecompare。
.sort(
function(a,b) {
a = a[1];
b = b[1];
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0; // Equal
}
});
添加回答
舉報