Skip to content

JavaScript array difference | Example get difference between two Arrays

  • by

How to get the difference between two arrays in JavaScript?

You can use filter() and includes() or map() second array and then use includes() to filter get out JavaScript array difference.

A cleaner approach in ES6 is the following solution. Using filter and includes methods:-

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

Difference

a2.filter(d => !a1.includes(d)) // gives ["c", "d"]

Examples of JavaScript array difference

Let’s see more HTML examples code of find difference of arrays in JS.

Example 1

It works only in one direction.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        //test
        var a1 = ['a', 'b'];
        var a2 = ['a', 'b', 'c', 'd'];
        
        var result = a2.filter(d => !a1.includes(d))
        alert(result);

    </script>
</head>
<body>

</body>
</html>

Output:

Example get difference between two Arrays javascript

Example 2

You could also map() second array and then use includes() to filter out duplicates.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">

        const allLanguages = [ 'ES', 'EN', 'DE' ]
        const usedLanguages = [ { id: 1, lang: 'EN' } ].map(e => e.lang);

        var result = allLanguages.filter(e => !usedLanguages.includes(e));
        console.log(result)

    </script>
</head>
<body>

</body>
</html>

Output:

Using for loop to a for .. in

If you are comparing a normal array. If not, you need to change the for loop to a for .. in the loop.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">

        function arr_diff (a1, a2) {

            var a = [], diff = [];

            for (var i = 0; i < a1.length; i++) {
                a[a1[i]] = true;
            }

            for (var i = 0; i < a2.length; i++) {
                if (a[a2[i]]) {
                    delete a[a2[i]];
                } else {
                    a[a2[i]] = true;
                }
            }

            for (var k in a) {
                diff.push(k);
            }

            return diff;
        }

        console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
        console.log(arr_diff("abcd", "abcde"));
        console.log(arr_diff("zxc", "zxc"));

    </script>
</head>
<body>

</body>
</html>

Do comment if you know a better example or have any doubts/suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading