Shortest Way To Remove Array Duplicates in ES6

0
2228
Remove Duplicate Value From Array
Remove Duplicate Value From Array

1. Set

Set is a introduced in ES6. Because Set only lets you store unique values. When you pass in an array, it will remove any duplicate values.

 

Example

const arr = [1,2,1,2,3,1];
let uniqueArray = [...new Set(arr)];
console.log(uniqueArray) //output : [1,2,3]

2. filter

Example

const arr = [1,2,1,2,3,1];
let uniqueArray = arr.filter((item,index)=> arr.indexOf(item)==index);
console.log(uniqueArray) //output : [1,2,3]

 

3. reduce

Example

const arr = [1,2,1,2,3,1];
let uniqueArray = arr.reduce((unique,item)=> unique.includes(item)? unique : [...unique, item],[]);
console.log(uniqueArray) //output : [1,2,3]

 

Working Example : https://jsfiddle.net/lochawala/f2sL9qkg/

LEAVE A REPLY

Please enter your comment!
Please enter your name here