0

I have misunderstood how to remove an element in an array which has a matching element to another array.

Example:

const items = ['first', 'second', 'third']
const secondItems = ['first', 'second']

Expected:

console.log(items) | 'third'
console.log(secondItems) | 'first', 'second

Hope some example how to achieve that. Tried many times with two forEach or filter and checking statement but I always get the wrong result.

Saeed
  • 2,169
  • 2
  • 13
  • 29
Dave
  • 507
  • 7
  • 22

3 Answers3

2

Simply use Array.prototype.filter() method:

const items = ['first', 'second', 'third']
const secondItems = ['first', 'second']

console.log(items.filter(i => !secondItems.includes(i)))
console.log(secondItems.filter(i => items.includes(i)))

I don't exactly understand this expectation of yours though:

console.log(secondItems) | 'first', 'second

Can you elaborate on that in the comments?

connexo
  • 53,704
  • 14
  • 91
  • 128
1

This could be solved by the following:

const items = ['first', 'second', 'third'];
const secondItems = ['first', 'second'];


const filteredBySecondItems = items.filter(function(item) {

  // For item in items array, check if there is a match
  // in secondItems. If there is no match, allow it
  // to be included in the returned list
  return secondItems.indexOf(item) === -1 

})

console.log(filteredBySecondItems) // [ 'third' ]
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
1
items.filter(x => !secondItems.includes(x))

Just tried in the browser console, it works.

mp92
  • 92
  • 5