Logo


How to remove duplicate values from array in javascript?


You will learn how to remove duplicate values from an array in javascript. There are many methods but we will teach you the two best and most common methods of removing duplicate values from the array.


1) Remove item from array with filter method.

1let arr = ['apple', 'banana', 'orange', 'mango', 'apple', 'orange'];
2
3    let uniqueValues = arr.filter((value, index) => {
4      return arr.indexOf(value) === index;
5    });
6    console.log(uniqueValues); //["apple", "banana", "orange", "mango"]

In the above example, we have removed duplicate values with the help of the filter method. The indexOf javascript method gets the index of the first appearance of value then we check if it is equal to the current index the return it otherwise skip it.


1) Remove item from array with Set method and spread operator.

1let arr = ['apple', 'banana', 'orange', 'mango', 'apple', 'orange'];
2    const uniqueValues = [...new Set(arr)]
3    console.log(uniqueValues);//["apple", "banana", "orange", "mango"]

The set method removed all duplicate values from the array. This is single line code which removes duplicates.



Related Articles :



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share