An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string but in case of JavaScript, we can store different type of elements. Using arrays you can organize data so that a related set of values can be easily sorted or searched.
This tutorial described to you to remove duplicate array elements using JavaScript.
Example
For example, create an array with some default values with adding duplicate array elements. Then remove all the duplicate array elements using JavaScript.
1 2 3 4 5 6 7 8 9 | function returnUnique(value, index, self) { return self.indexOf(value) === index; } // usage example: var arr = ['Green', 'Red', 100, 'Green', 20, '100']; var unique = arr.filter(returnUnique); console.log(unique); // |
Output:
["Green", "Red", 100, 20, "100"]
In the above example, value “Green” was defined twice in the array. As a result, you see only one instance of Green.
You may thinking about the element 100. Let me clear that the first occurrence of the element 100 is an integer value and the second one is defined as string. In short both the elements are treated as unique.
Leave a Reply