How to Get Only Unique Values From Array in JavaScript?

18-May-2023

.

Admin

How to Get Only Unique Values From Array in JavaScript?

I will explain step by step tutorial how to get only unique values from array in javascript. you can understand a concept of get all unique values in a javascript array. I would like to show you how to get distinct values from an array of objects in javascript. you will learn how to get all unique values get in a javascript.

There are several ways to get only unique values from an array in JavaScript:

1. Using the Set object: The Set object is a built-in data structure in JavaScript that allows you to store unique values of any type. You can convert an array into a Set using the spread operator and then convert it back to an array using the Array.from() method.

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get Only Unique Values From Array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3, 2, 4, 3];

const uniqueArr = Array.from(new Set(arr));

console.log(uniqueArr); // [1, 2, 3, 4]

</script>

</html>

2. Using the filter() method: You can use the filter() method to create a new array with only unique values by checking if the index of each element is equal to its first occurrence in the array.

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get Only Unique Values From Array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3, 2, 4, 3];

const uniqueArr = arr.filter((value, index) => {

return arr.indexOf(value) === index;

});

console.log(uniqueArr); // [1, 2, 3, 4]

</script>

</html>

3. Using the reduce() method: You can use the reduce() method to create a new array with only unique values by checking if the current value is already present in the accumulator array.

Example 3:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get Only Unique Values From Array in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3, 2, 4, 3];

const uniqueArr = arr.reduce((accumulatorArray , currentValue) => {

if(!accumulatorArray.includes(currentValue)){

accumulatorArray.push(currentValue);

}

return accumulatorArray;

}, []);

console.log(uniqueArr); // [1, 2 ,3 ,4]

</script>

</html>

All these methods will give you an array with only unique values.

#JavaScript