Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate item from array Javascript [duplicate]

I'm looking for an easy way of removing a duplicate value from an array. I figured out how to detect if there is a duplicate or not, just I don't know how to "push" it from the value. For example, if you go to the link provided, and then type, "abca" (press return/enter key after each letter).. it will alert "duplicate!"

But I also want to figure out how to remove that duplicate from the textarea?

http://jsfiddle.net/P3gpp/

This is the part that seems to not be working ::

sort = sort.push(i);
textVal = sort;
return textVal;
like image 497
Matthew Avatar asked Aug 02 '13 02:08

Matthew


People also ask

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

How can you eliminate duplicate values from a JavaScript array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do you remove duplicate values from an array of objects?

To remove the duplicates from an array of objects: Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you get all unique values remove duplicates in a JavaScript array?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values. There are other approaches like: Using new ES6 feature: [… new Set( [1, 1, 2] )];


2 Answers

Why do it the hard way, it can be done more easily using javascript filter function which is specifically for this kind of operations:

var arr = ["apple", "bannana", "orange", "apple", "orange"];

arr = arr.filter( function( item, index, inputArray ) {
           return inputArray.indexOf(item) == index;
    });


---------------------
Output: ["apple", "bannana", "orange"]
like image 157
user2668376 Avatar answered Oct 12 '22 23:10

user2668376


Based on user2668376 solution, this will return a new array without duplicates.

Array.prototype.removeDuplicates = function () {
    return this.filter(function (item, index, self) {
        return self.indexOf(item) == index;
    });
};

After that you can do:

[1, 3, 3, 7].removeDuplicates();

Result will be; [1, 3, 7].

like image 22
Frank Roth Avatar answered Oct 13 '22 01:10

Frank Roth