javascript
Remove duplicate items from array in Javascript
We are going to explain methods with code examples in this post that can be used to remove duplicate values from an array using Javascript.
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]
Remove duplicates using spread syntax
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"]
Using For Loop (Fast Performance)
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"]
Was this helpful?
Similar Posts
- Remove duplicate values from an array in Javascript
- How to Remove duplicate elements from array in JavaScript ?
- Join two arrays and remove duplicate elements using Javascript
- Check if array contains duplicate values in Javascript
- Get all values as array items from an Object in Javascript
- Check if all array items are equal javascript
- Assign items of arrays to multiple variable when creating it (Array Destructuring) Javascript(ES6)