3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
你可以拿一個(gè) Set
該Set對(duì)象允許您存儲(chǔ)任何類型的唯一值,無論是原始值或?qū)ο笠谩?/p>
并從左側(cè)和右側(cè)返回差值。
function getSymDifference(a, b) {
return getDifference(a, b).concat(getDifference(b, a));
}
function getDifference(a, b) {
var setB = new Set(b);
return a.filter(v => !setB.has(v));
}
console.log(getSymDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])); // ["pink wool"]
console.log(getSymDifference([1, "calf", 3, "piglet"], [7, "filly"])); // [1, "calf", 3, "piglet", 7, "filly"]
console.log(getSymDifference([], ["snuffleupagus", "cookie monster", "elmo"]));
console.log(getSymDifference([1, 2, 3, 5], [1, 2, 3, 4, 5]));
通過拼接數(shù)組以防止再次使用已訪問或搜索的項(xiàng)目的經(jīng)典方法。
function getSymDifference(a, b) {
var aa = a.slice(),
bb = b.slice(),
result = [],
i, j;
for (i = 0; i < aa.length; i++) {
j = bb.indexOf(aa[i]);
if (j === -1) {
result.push(aa[i]);
} else {
bb.splice(j, 1);
}
}
return result.concat(bb);
}
console.log(getSymDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])); // ["pink wool"]
console.log(getSymDifference([1, "calf", 3, "piglet"], [7, "filly"])); // [1, "calf", 3, "piglet", 7, "filly"]
console.log(getSymDifference([], ["snuffleupagus", "cookie monster", "elmo"]));
console.log(getSymDifference([1, 2, 3, 5], [1, 2, 3, 4, 5]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
舉報(bào)