0

Hello i'm a beginner in nodejs and i just wanted to know how can i compare 2 array and store the difference into an other array.

i've done this to start :

const array1 = [1,2,3,4,5,6,7,8,9,0];
const array2 = [5,2,8,9];
const array3 = []; //wanted [1,3,4,6,7,0]
var i=0
array2.forEach(function(element){
  const found = array1.find(element => element !== array2[i])
    array3.push(found)
  i++
})
  console.log(array3)

Thanks a lot !

2 Answers 2

1

You could use filter and includes

const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
const array2 = [5, 2, 8, 9]
const array3 = array1.filter((element) => !array2.includes(element))
console.log(array3)

Sign up to request clarification or add additional context in comments.

Comments

1

You can implement that using Array.filter & Array.includes function.

const array1 = [1,2,3,4,5,6,7,8,9,0];
const array2 = [5,2,8,9];

const result = array1.filter(item => !array2.includes(item));
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.