How to remove duplicates from JavaScript Array?

devquora
devquora

Posted On: Feb 22, 2018

 

There are many ways to remove duplicates from JavaScript array. These are described below with examples:

1. By using Set: It is the simplest approach to remove duplicates. Set is an inbuilt object to store unique values in an array. Here's how we use set:

    function uniquearray(array) { 
       let unique_array= Array.from(set(array)) 
       return unique_array;}

As in the above code, you created a set of an array which automatically eliminates the duplicate values.

2. By using Filter: Another approach to remove duplicates from an array is applying filter on an array. To call filter method, it requires three arguments: array, current element, index of current element. Here’s how we use filter:

function unque_array (arr){
 let unique_array = arr.filter(function(elem, index, self) {
 return index == self.indexOf(elem); } 
return unique_array }
 console.log(unique_array(array_with_duplicates));

3. By using for loop: In this, we can use for loop to remove duplicates. In this we make an empty array in which those elements will be added from the duplicate array which are not present in this before. Thus, finally we will get an array which has unique elements. Code to implement this:

Array dups_names = ['Ron', 'Pal', 'Fred', 'Rongo', 'Ron'];
function dups_array(dups_names) {
 let unique = {};
 names.forEach(function(i) {
    If (!unique[i]) {
      unique[i] = true;    }
  });
return Object.keys(unique);}   // Ron, Pal, Fred, Rongo
Dups_array(names);

These are the main three methods used in JavaScript to get a unique array.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    JavaScript Interview Questions

    Explain what is Javascript?

    JavaScript, a dynamic, client-side language, is crucial in modern web development, working alongside HTML and CSS. Its manipulation of the Document Object Model (DOM) enables dynamic content and inter..

    JavaScript Interview Questions

    What close() does in Javascript?

    In JavaScript, the close() method is employed to securely close the current window. To ensure its association with the window object rather than another JavaScript object, employ window.close(). This ..

    JavaScript Interview Questions

    What is the difference between let and var?

    Both var and let are utilized for variable/method declaration in JavaScript. The crucial disparity lies in their scope: var is function-scoped, meaning it's accessible throughout the function it's def..