How to get the difference between two arrays in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To get the difference between two arrays in JavaScript, try to run the following code. Here, we’re using some method like split(), indexOf(), sort(), etc to get the elements, which aren’t the same in both the arrays &mnus;

Example

Live Demo

<html>
   <head>
      <title>JavaScript Dates</title>
   </head>
   <body>
      <script>
         function arrDifference (arr1, arr2) {
            var arr = [];
            arr1 = arr1.toString().split(',').map(Number);
            arr2 = arr2.toString().split(',').map(Number);
            // for array1
            for (var i in arr1) {
               if(arr2.indexOf(arr1[i]) === -1)
               arr.push(arr1[i]);
            }
            // for array2
            for(i in arr2) {
               if(arr1.indexOf(arr2[i]) === -1)
               arr.push(arr2[i]);
            }
            return arr.sort((x,y) => x-y);
         }
         document.write(arrDifference([50, 40, 90], [70, 50, 99, 40, 90]));
      </script>
   </body>
</html>

Output

70,99
raja
Published on 12-Feb-2018 13:38:17
Advertisements