4 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
在對(duì)字符串值進(jìn)行排序時(shí),應(yīng)使用該方法。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貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
您是否希望數(shù)組與第一個(gè)實(shí)例中的數(shù)據(jù)格式相同?
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貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
我會(huì)創(chuàng)建一個(gè)查找對(duì)象并保留對(duì)數(shù)組項(xiàng)的引用。在循環(huán)訪問當(dāng)前項(xiàng)目后,我將循環(huán)訪問新項(xiàng)目。檢查它是否存在并更新計(jì)數(shù)。如果不存在,則將物料添加到庫(kù)存中。
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貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
對(duì)字符串進(jìn)行排序時(shí),它有點(diǎn)復(fù)雜,因?yàn)槟€必須考慮大小寫。這是我在js中制作的表格中的一個(gè)片段,希望它有所幫助。您也可以像 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
}
});
添加回答
舉報(bào)