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
  • 1,718
  • 1
  • 10
  • 24
Dave
  • 437
  • 4
  • 16

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
  • 41,035
  • 12
  • 60
  • 87
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
  • 26,362
  • 5
  • 28
  • 48
1
items.filter(x => !secondItems.includes(x))

Just tried in the browser console, it works.

mp92
  • 84
  • 5