How to remove duplicate values from JavaScript array ?
Using jQuery:
var names = ["Mark Twain", "John Steinbeck", "William Faulkner", "William Faulkner", "Robert Frost", "Walt Whitman", "William Faulkner"]; var uniqueNames = []; $.each(names, function(i, el){ if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); });
Use this code.
let names = ['Mark Twain', 'John Steinbeck', 'William Faulkner', 'William Faulkner', 'Robert Frost', 'Walt Whitman', 'William Faulkner']; let dup = [...new Set(names)]; console.log(dup);
This code using an array filter and indexOf functions:
arr = arr.filter (function (value, index, array) { return array.indexOf (value) == index; });
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));
UniqueArray contains no duplicates.
var Array = duplicateArray.filter(function(elem, pos) { return duplicateArray.indexOf(elem) == pos; });