Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to get the elements of one array which are not present in another array using JavaScript?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The task is to get the elements of one array that are not present in another array. Here we are going to use JavaScript to achieve the goal. Here are a few techniques discussed. 

Approach

  • Take the arrays in variables.
  • Use the .filter() method on the first array and check if the elements of the first array are not present in the second array, Include those elements in the output.

Example 1: This example uses the approach discussed above. 

html




<h1 id="h1" style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP"></p>
<button onclick="gfg_Run()">
    Click here
</button>
<p id="GFG_DOWN"></p>
<script>
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
    var ar1 = [1, 2, 3, 4];
    var ar2 = [2, 4];
    el_up.innerHTML =
    "Click on the button to remove the element of "+
    "second from the first array.<br><br> firstArray - " +
    ar1 + "<br>secondArray - " + ar2;
      
    function gfg_Run() {
        var elmts = ar1.filter(
            function(i) {
                return this.indexOf(i) < 0;
            },
            ar2
        );
        el_down.innerHTML = elmts;
    }
</script>

Output:

How to get the elements of one array which are not present in another array using JavaScript?

How to get the elements of one array which are not present in another array using JavaScript?

Example 2: This example uses the same approach but different methods of JavaScript. 

html




<h1 id="h1" style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP"></p>
<button onclick="gfg_Run()">
    Click here
</button>
<p id="GFG_DOWN"></p>
<script>
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
    var ar1 = [1, 2, 3, 4];
    var ar2 = [2, 4];
    el_up.innerHTML =
    "Click on the button to remove the element of second"+
    " from the first array.<br><br> firstArray - "
    + ar1 + "<br>secondArray - " + ar2;
      
    function gfg_Run() {
        var elmts = ar1.filter(f => !ar2.includes(f));
        el_down.innerHTML = elmts;
    }
</script>

Output:

How to get the elements of one array which are not present in another array using JavaScript?

How to get the elements of one array which are not present in another array using JavaScript?


My Personal Notes arrow_drop_up
Last Updated : 23 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials