最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I reverse the "includes()" method to "not-includes()" and retrieve the

programmeradmin1浏览0评论

Im trying to retrieve the not included value in the second array, by using the following code:

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])
)

Im trying to retrieve the not included value in the second array, by using the following code:

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])
)

Is there any way I can use another method to do this. I tried indexOf but I don't want the index.

Thank you

Share Improve this question edited Dec 16, 2019 at 16:03 adiga 35.3k9 gold badges65 silver badges87 bronze badges asked Dec 16, 2019 at 15:44 Tiago RuivoTiago Ruivo 1832 silver badges11 bronze badges 1
  • use ! . That means not – TKoL Commented Dec 16, 2019 at 15:45
Add a ment  | 

3 Answers 3

Reset to default 4

You can use 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);

if (!arr2.includes(i)) {
     newArr.push(i)
   } 

! means not

You could always use else as well, but it's more lines of code:

if (arr2.includes(i)) {
     // newArr.push(i)
 }  else {
    newArr.push(i);
}
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);
}
发布评论

评论列表(0)

  1. 暂无评论