Javascript,Nodejs,MongodDB,WordPress,CSS,PHP

LightBlog

Wednesday, July 7, 2021

How to remove duplicates element from array

In this post i'm going to remove duplicates element from array,i will try with multiple approaches to remove duplicates element from array.

Method 1 Using Set

const array = ["a","b","c","d","a","c","e","f"];
const m1 = [...new Set(array)];
console.log(m1); // ["a", "b", "c", "d", "e", "f"] 

Method 2 Using object

const array = ["a","b","c","d","a","c","e","f"];
let obj = {};
for (let arr of array){
obj[arr]=true;
}
console.log(Object.keys(obj)); // ["a", "b", "c", "d", "e", "f"] 

Method 3 Using Loop

const array = ["a","b","c","d","a","c","e","f"];
const m3 = [];
var i;
var len = array.length
for(i = 0;i
Method 4 Using Filter

const array = ["a","b","c","d","a","c","e","f"];
const m4 = array.filter((el,index)=>array.indexOf(el) == index);
console.log(m4); // ["a", "b", "c", "d", "e", "f"]

No comments:

Post a Comment