Remove duplicate array via vanilla JavaScript

In this, another small tutorial I am going to show you how you simply remove the duplicate array from any array given. This is a very simple trick, so you don’t require any other plugin or framework. I am going to show you how to remove duplicate array via vanilla JavaScript only.

Remove duplicate array via vanilla JavaScript easy

var duplicateArray = [1,1,1,5,6,3,2,8,9,5,2,2,4,4];
var cleanArray = [];

In the above array, we have many duplicate numbers we see. Now in order to remove duplicate value from the array, we run a loop. Also, we initialize a new blank array, where we are going to push all the unique items removing duplicate array.

for(var i=0; i<duplicateArray.length; i++){ 
    if(cleanArray.indexOf(duplicateArray[i]) === -1){ 
         cleanArray.push(duplicateArray[i])
    } 
}

The first line for(var i=0; i, simply states that we are inititating for loop for duplicateArray.

The second line if(cleanArray.indexOf(duplicateArray[i]) === -1){ , we are checking if the loop item `duplicateArray[i]` doesn’t exist in our new blank array so called cleanArray[]. So if the loop item is not present in the cleanArray[] then we push the loop inside the cleanArray[]. The -1 return when the indexOf() method doesn’t find the position of loop value.

In the next third line we simply push the new item filter from the second line to our cleanArray[]

Hope it helps anyone.

Leave a Reply

Your email address will not be published. Required fields are marked *