Remove duplicates from a given array in Javascript:
There are a lot of methods to remove duplicate elements from an array.
Solution 1
I am trying to write a javascript code that takes a for loop and sets a value into a new array
function removeDuplicates(array) { var indexValue = {}; array.forEach(function(i) { if(!indexValue[i]) { indexValue[i] = true; } }); return Object.keys(indexValue); } var array = [1, 1, 3, 5, 3, 5,4]; console.info((array)); console.info(removeDuplicates(array));
Solution 2
Use the jquery
var array = [1, 1, 3, 5, 3, 5,4]; var uniqueArray=[]; $.each(array, function(i, el){ if($.inArray(el, uniqueArray) === -1) uniqueArray.push(el); }); console.info((uniqueArray));
Solution 3
Using the set constructor
var array = [1, 1, 3, 5, 3, 5,4]; var uniqueArray = new Set(array); console.info((uniqueArray));
Also, read Fair of element