JavaScript by Radu TM • June 21, 2022
// difference between two arrays in JavaScript
const firstArray = [1, 2, 3, 4, 5];
const secondArray = [5, 2, 10];
// use the Set object to store unique values from the first array
const firstSet = new Set(firstArray);
console.log(firstSet); // Set { 1, 2, 3, 4, 5 }
// use the Set object to store unique values from the second array
const secondSet = new Set(secondArray);
console.log(secondSet); // Set { 5, 2, 10 }
// create a new Set that contains values that are in the firstSet but not the secondSet
const differenceSet = new Set([...firstSet].filter(x => !secondSet.has(x)));
console.log(differenceSet); // Set { 1, 3, 4 }
0
25.028
JavaScript by Radu TM • June 21, 2022
// Get the difference between two arrays in JavaScript
const array1 = ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊'];
const array2 = ['🐭', '🐹', '🐰'];
// Use the filter() method to create a new array with only the elements from array1 that are not present in array2
const difference = array1.filter(x => !array2.includes(x));
console.log(difference);
// Output: ['🐶', '🐱', '🦊']
0
25.028