DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Comparing Two Different Arrays

  • Second we will simply compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. Remember the keyword "not both".
  • Problem Below:
function arrays(arr1, arr2) { } arrays([1, 2, 4, 5], [1, 2, 3, 4, 5]); 
Enter fullscreen mode Exit fullscreen mode

Answer:

function arrays(arr1, arr2) { let merge = arr1.concat(arr2); return merge.filter(function(num) { // <--- num are all the numbers in merge. [1, 2, 4, 5, 1, 2, 3, 4, 5] if (arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1) { return num; } }) } console.log(arrays([1, 2, 4, 5], [1, 2, 3, 4, 5])); // will display [3] 
Enter fullscreen mode Exit fullscreen mode
  • We're just checking the two arrays and return a new array that contains only the items that are not in either of the original arrays. In this case 3.
  • What we did was merge the list to make it easy to compare and used filter to get the new array in which you will need to create a callback function.

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Your filter function only need return true or false, and as @adam_cyclones points out, you should really only check the unique values in the merged array (no point checking the same numbers more than once):

function diffArray(arr1, arr2) { let merge = [...new Set([...arr1, ...arr2])] return merge.filter(function(num) { return arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1 }) } 
Enter fullscreen mode Exit fullscreen mode

or, shorter:

const diffArray = (arr1, arr2) => [...new Set([...arr1, ...arr2])].filter( num => arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1 ) 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

I saw something useful when creating an exlusion list. Use a Set on the second array to reduce complexity in code and speed things up. Perfect for es6 > targets

Collapse
 
devfranpr profile image
DevFranPR

Nice one