Home > Software engineering >  How do I remove one arrays contents from another arrays elements?
How do I remove one arrays contents from another arrays elements?

Time:11-28

I have two arrays as codely illustrated below:

let arrayOne = [1669683600000, 1669770000000, 1669698000000, 1669755600000];
let arrayTwo = [1669683600000, 1669770000000];

I would like to remove the contents of arrayTwo from arrayOne. I thought the code below would work:

let results = arrayOne.filter((item)=> item !== arrayTwo);
console.log('results: ' ,results );

The code above yeilds:

results: [1669683600000, 1669770000000, 1669698000000, 1669755600000]    

The desired results are:

results: [1669698000000, 1669755600000]

How do I achieve my desired results?

CodePudding user response:

Use filter but only include the item if it is not(!) in(includes) arrayTwo

let arrayOne = [1669683600000, 1669770000000, 1669698000000, 1669755600000];
let arrayTwo = [1669683600000, 1669770000000];

console.log(arrayOne.filter((item)=>!arrayTwo.includes(item)))

CodePudding user response:

Using filter

arrayOne = arrayOne.filter(function(val) {
  return arrayTwo.indexOf(val) == -1;
});
  • Related