How to remove the duplicate Elements from an array in JavaScript ?

How to remove the duplicate Elements from an array in JavaScript ?

·

3 min read

Table of contents

No heading

No headings in the article.

const numArray = [0,1,1,2,2,2,3,3,5,5,5] // input
//expected output [0,1,2,3,5]
  1. Using the indexOf & filter method

    indexOf: MDN says, the indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

     const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
    
     console.log(beasts.indexOf('bison'));
     // Expected output: 1
    
     // Start from index 2
     console.log(beasts.indexOf('bison', 2));
     // Expected output: 4
    
     console.log(beasts.indexOf('giraffe'));
     // Expected output: -1
    

    filter: MDN says, the filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

     const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    
     const result = words.filter(word => word.length > 6);
    
     console.log(result);
     // Expected output: Array ["exuberant", "destruction", "present"]
    

    By now I'm expecting you to be familiar with the filter and indexOf method. So, let's solve the problem

    ```javascript //Solution using filter & indexOf method const numArray = [0,1,1,2,2,2,3,3,5,5,5] ; const removeDuplicateElements = (nums) =>{ // a filter can take 4 params // -> a callback function // -> current element // -> index of current element // -> the input array itself

const filtredNums = nums.filter((currentElement, index) => nums.indexOf(currentElement) === index);

return filtredNums }

//console.log(removeDuplicateElements(numArray)) //expected output [0,1,2,3,5]


2. Using the **forEach** method

    **forEach:** [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) says, the `forEach()` method executes a provided function once for each array element.

    ```javascript
    const array1 = ['a', 'b', 'c'];

    array1.forEach(element => console.log(element));

    // Expected output: "a"
    // Expected output: "b"
    // Expected output: "c"

Let's solve this then,

    // solution using forEach()
    const numArray = [0,1,1,2,2,2,3,3,5,5,5, "harry", "harry", "potter"] ;
    const removeDuplicateElements = (nums) =>{
       let obj = {}
       nums.forEach(currentElement => {
        if(!obj[currentElement]){
          obj[currentElement] = 1
     }else{
    obj[currentElement] += 1
    }
      })
    const filteredElements = Object.keys(obj)
    return filteredElements
    }
    console.log(removeDuplicateElements(numArray))
    // Expected Output -> ["0","1","2","3","5","harry","potter"]

Note: In this solution, we receive all the elements in the form of strings. So, you can ask yourself a question here, why? You can let me know your answer by commenting below in the comment section.

  1. Using the map()

    map: MDN says, the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

     const array1 = [1, 4, 9, 16];
    
     // Pass a function to map
     const map1 = array1.map(x => x * 2);
    
     console.log(map1);
     // Expected output: Array [2, 8, 18, 32]
    

    You already know the map method, so let's do it,

     const numArray = [0,1,1,2,2,2,3,3,5,5,5, "harry", "harry", "potter", 1,9] ;
     const removeDuplicateElements = (nums) =>{
      const arr = [];
       nums.map(item => !arr.includes(item) && arr.push(item))
       return arr
     }
     console.log(removeDuplicateElements(numArray))
     // Expected output : [0,1,2,3,5,"harry","potter",9]
    

    Out of above mentioned three steps which one do you like most, let me know by commenting below.
    Thanks for investing your time, if you have any feedback please let me know I would be thankful.