0

I'm trying to compare two arrays.

firstArray has 451 integers in it, secondArray has 91 integers in it.

All integers that are in secondArray are also in firstArray.

I want to log out the integers from firstArray that are not in secondArray.

I tried the following :

 for (let i = 0; i < firstArray.length; i++) {
  for (let j = 0; j < secondArray.length; j++) {
     if (firstArray[i] !== secondArray[j]) {
       console.log(firstArray[i])
} } } 

But it returned all 451 integers from the firstArray where I expected it to return 360 integers (firstArray - secondArray)

It's my first time posting here, hope it's clear enough ahah.

Adaen
  • 3
  • 2

1 Answers1

-1

Use flags to keep track of which parts are in the set and which are not.

const arrOne = [34,2,12,4,76,7,8,9]
const arrTwo = [8,12,2]
let isInSet = false
const notInSet = []

// Expected output: 34, 4, 76, 7, 9

arrOne.forEach((el, i) => {
  isInSet = false
  arrTwo.forEach((curr, j) => {
    if (el == curr) {
      isInSet = true
    }
  })
  
  if (!isInSet) {
    notInSet.push(el)
  } 
})

console.log(notInSet)
// OR spread them out
console.log(...notInSet)
Vladimir Mujakovic
  • 650
  • 1
  • 7
  • 21