我正在尝试通过使用以下代码来检索第二个数组中的不包括的值:
function diffArray(arr1, arr2) {
var newArr = [];
for (let i of arr1) {
if (arr2.includes(i)) {
newArr.push(i)
}
}
return newArr
}
console.log(
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])
)
有什么办法可以使用另一种方法来做到这一点。我尝试了indexOf,但是我不想索引。
谢谢
答案 0 :(得分:2)
您可以使用filter()
:
let arr1 = [1, 2, 3, 5];
let arr2 = [1, 2, 3, 4, 5];
let result = arr2.filter(a2 => !arr1.includes(a2));
console.log(result);
答案 1 :(得分:1)
if (!arr2.includes(i)) {
newArr.push(i)
}
!意味着不是
您也可以始终使用else
,但这需要更多代码行:
if (arr2.includes(i)) {
// newArr.push(i)
} else {
newArr.push(i);
}
答案 2 :(得分:0)
const a1 = [1, 2, 3, 4, 5];
const a2 = [1, 2, 3, 5];
function diffArray(arr1, arr2) {
const frequencies = arr1.concat(arr2).reduce((frequencies, number) => {
const frequency = frequencies[number];
frequencies[number] = frequency ? frequency + 1 : 1;
return frequencies;
}, {});
return Object.keys(frequencies).filter(number => frequencies[number] === 1);
}