-1

I am using the below javascript to create a multi-select option in html and the values are showing as selected based on the values stored in another json, the problem is the values are getting duplicated like below and i dont know how to remove the duplicate values showing in multi-select. Is there a way to remove the duplicate values in javascript and show the data without any duplicate values?

SimbuStar
  • 623
  • 1
  • 7
  • 18

2 Answers2

0

Remove Duplicates from JavaScript Array Using For Loop

let array_with_duplcates = ['DELHI','NEWYORK','DELHI','GOA','MUMBAI','CALIFORNIA','GOA']

    function removeDuplicates(arr){
        let unique_array = []
        for(let i = 0;i < arr.length; i++){
            if(unique_array.indexOf(arr[i]) == -1){
                unique_array.push(arr[i])
            }
        }
        return unique_array
    }

    console.log(removeDuplicates(array_with_duplcates)); // [ 'DELHI', 'NEWYORK', 'GOA', 'MUMBAI', 'CALIFORNIA' ]

Remove Duplicates From JavaScript Array Using Filter Method

function removeDuplicateUsingFilter(arr){
    let unique_array = arr.filter(function(elem, index, self) {
        return index == self.indexOf(elem);
    });
    return unique_array
}

console.log(removeDuplicateUsingFilter(array_with_duplicates));

Remove Duplicates From JavaScript Array Using Set

function removeDuplicateUsingSet(arr){
    let unique_array = Array.from(new Set(arr))
    return unique_array
}

console.log(removeDuplicateUsingSet(array_with_duplicates));

Removing Duplicates Using Lodash Library

0

I wonder if you're okay using lodash.js It's got some nice features for it (try uniq or uniqBy) and it's very lightweight.

fpintodacosta
  • 98
  • 1
  • 8