Remove duplicate values from JS array [duplicate]

ghz 1years ago ⋅ 7235 views

Question

This question already has answers here :

[Get all unique values in a JavaScript array (remove duplicates)](/questions/1960473/get-all-unique-values-in-a-javascript-array- remove-duplicates) (96 answers)

Closed 6 years ago.

The community reviewed whether to reopen this question 23 days ago and left it closed:

Original close reason(s) were not resolved

I have a very simple JavaScript array that may or may not contain duplicates.

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:


Answer

Quick and dirty using jQuery:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});