let numbers = [1, 3, 1, 5, 4, 3, 5];
numbers = numbers.filter(function (item, index) {
return numbers.indexOf(item) == index;
});
console.log(numbers)
Output
[1,3,5,4]
We all are familiar with the spread syntax in javascript and use it for many processes. We can also use it for removing duplicate elements from the array.
Syntax
[...new Set(array)]
Code Example
const arr = ['b', 'c', 'b', 'd', 'a', 'b', 'c'];
const distinct_arr = [...new Set(arr)];
console.log(distinct_arr);
Output
["b","c","d","a"]
We can also use Javascript For Loop to get the unique array from an array that contains duplicate values. As we know that using functions can cost performance degrade in Javascript so we do that in the old way.
Code Example
const arr = ['b', 'c', 'b', 'd', 'a', 'b', 'c'];
var added = {};
var result = [];
var j = 0;
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (added[item] !== 1) {
added[item] = 1;
result[j++] = item;
}
}
console.log(result);
Output
["b","c","d","a"]
0 Comments