Use set and filter to find the difference between two arrays.
let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; let difFruits = [...new Set(fruits1)].filter((item) => !fruits2.includes(item)); console.log(difFruits); // [ 'orange', 'grapes' ] Similarly if you want to find the elements common in both arrays, you could employ a slightly different strategy.
let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; let commonFruits = [...new Set(fruits1)].filter((item) => fruits2.includes(item) ); console.log(commonFruits); // [ 'apple' ] Traditionally, you would have executed two loops to find differences between arrays. Something like -
let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; const difFruits = []; for (fruitOne of fruits1) { let found = false; for (fruitTwo of fruits2) { if (fruitTwo == fruitOne) { found = true; break; } } // fruits2 loop if (!found) difFruits.push(fruitOne); } // fruits1 loop console.log(difFruits); // [ 'orange', 'grapes' ] We live in exciting times for sure.