Here is a simple way to remove duplicate elements from an array in JavaScript. Just loop through the actual array and push each element in another temporary unique array. Before pushing an element into unique array, make sure to check if the element already exist (in unique array). To learn more about how to check if a value exist in an array, you can read this article: How to Check If a Value Exists in an Array in JavaScript
var fruits = ["Apple", "Banana", "Mango", "Apple", "Papaya"];
var unique = [];
fruits.forEach(function(element){
// Push if the element does nor exist in unique array
if(unique.indexOf(element) === -1){
unique.push(element);
}
})
console.log(unique);
// Output:
["Apple", "Banana", "Mango", "Papaya"]
This approach does not alter the order of elements. It will just eliminate duplicate values and keep the unique elements in the same order.
ES6 Approach:
Using ES6, you can get same result in just a single line of code as shown in the example below:
var fruits = ["Apple", "Banana", "Mango", "Apple", "Papaya"];
var unique = Array.from(new Set(fruits));
console.log(unique);
// Output:
["Apple", "Banana", "Mango", "Papaya"]
Please note that this code may not work in IE browser.