3 回答

TA贡献1824条经验 获得超5个赞
你可以拿一个 Set
该Set对象允许您存储任何类型的唯一值,无论是原始值或对象引用。
并从左侧和右侧返回差值。
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]));
通过拼接数组以防止再次使用已访问或搜索的项目的经典方法。
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; }
添加回答
举报