Javascript unique value in array

How to Get All Unique Values from Array in JavaScript

Here are the methods to get all unique values from an array in JavaScript.

Method 1: Using the new Set() constructor

To get all unique values and remove all the duplicates from the array in JavaScript, the easiest way is to use the “[…new Set(arr)]” expression, where you pass the array to the Set() constructor, and it will return the array with unique values.

const names = ['kb', 'kl', 'kk', 'kb', 'kl', 'ka'] const unique_names = [. new Set(names)] console.log(unique_names)

In the above code example, we defined an array called names with six elements and then created a new array called unique_names that contains only the unique elements from the names array.

Читайте также:  Groups ismember vk api python

The Set object is used to create a collection of unique values.

By spreading a new Set(names) into a new array using the spread syntax …, we can convert the Set object back into an array.

The resulting array unique_names contains only the unique values from the original names array.

Method 2: Using filter + indexOf() methods

The filter() is a built-in array method that creates a new array with all elements that pass the test implemented by the provided function.

The indexOf() is a built-in array method that returns the first index at which a given element can be found in the array, or -1 if not present.

Write the following code inside the app.js file.

const unique = (value, index, self) =>  return self.indexOf(value) === index > const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.filter(unique) console.log(uniqueAges)

In the above function, we have used the two in-built JavaScript functions.

The array filter() and array indexOf(). We have also used an arrow function, a feature of ES6.

So, in the above code, we filter out each repetitive value using the filter function and pass the unique callback to each array element.

How To Get Distinct Values From Array In Javascript

Method 3: Using the filter() method

The array.filter() function is “used to create a new array from an existing array which satisfies a condition set by the argument function.”

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.filter((x, i, a) => a.indexOf(x) == i) console.log(uniqueAges)

Method 4: Using a set and spread operator

In ES6, the code is much simpler. For example, the code snippet below utilizes the Set object to store the collection of unique values; then, we used the spread operator to construct the new Array.

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = [. new Set(ages)] console.log(uniqueAges)

The constructor of the set takes an iterable object, like an Array, and the spread operator transform the group back into an Array.

The output is the following.

Get Unique Values using Javascript Set

Method 5: Using Set and Array from a method

Use the Set and array from() method to get unique values. It will eliminate duplicate values from an array.

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const result = Array.from(new Set(ages)); console.log(result)

It will give us the same output.

Method 6: Defining our own Array Unique Prototype

We can also define the prototype that can give us the unique value of the Array. Our prototype function will be the following.

Array.prototype.unique = function()  var arr = []; for(var i = 0; i < this.length; i++)  if(!arr.includes(this[i]))  arr.push(this[i]); > > return arr; >

Call the Array Unique function on an array and see the output.

Array.prototype.unique = function()  let arr = []; for(let i = 0; i < this.length; i++)  if(!arr.includes(this[i]))  arr.push(this[i]); > > return arr; > const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.unique() console.log(uniqueAges)

Define our own Array Unique Prototype

2 thoughts on “How to Get All Unique Values from Array in JavaScript”

This gives the answer 2. But how can I avoid “converting” 2D points to a string?
[…new Set([[0, 0], [0, 0], [1, 0]].map(_ => _.join(‘:’)))].length Thanks Reply

Amazing article. after a long search i got this and the various ways of getting the unique values is really interesting
I have one requirement where i have to get unique values from a json array. Each array element has multiple attributes. let us say there are 4 attributes in an element. i want to get unique elements based on attribute 2. eg. the json data is:
“dept”:’HR’, “role”:Manager,”name”:’Moorthi’;
“dept”:’HR’, “role”:Manager,”name”:’Ramesh’;
“dept”:’HR’, “role”:Recruiter,”name”:’Suresh’;
“dept”:’Finance’, “role”:Manager,”name”:’Krunal’;
“dept”:’Finance’, “role”:Auditor,”name”:’Sachin’;
“dept”:’Finance’, “role”:Auditor,”name”:’Ashwin’; I want to get depts as ‘HR’, ‘Finance’ and also if the Dept is HR then the roles in that are like ‘Manager’ and ‘Recruiter’. Any help in this regard is appreciated. Thanks in advance for the help Reply

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

How to Get All Unique Values from Array in JavaScript

Here are the methods to get all unique values from an array in JavaScript.

Method 1: Using the new Set() constructor

To get all unique values and remove all the duplicates from the array in JavaScript, the easiest way is to use the “[…new Set(arr)]” expression, where you pass the array to the Set() constructor, and it will return the array with unique values.

const names = ['kb', 'kl', 'kk', 'kb', 'kl', 'ka'] const unique_names = [. new Set(names)] console.log(unique_names)

In the above code example, we defined an array called names with six elements and then created a new array called unique_names that contains only the unique elements from the names array.

The Set object is used to create a collection of unique values.

By spreading a new Set(names) into a new array using the spread syntax …, we can convert the Set object back into an array.

The resulting array unique_names contains only the unique values from the original names array.

Method 2: Using filter + indexOf() methods

The filter() is a built-in array method that creates a new array with all elements that pass the test implemented by the provided function.

The indexOf() is a built-in array method that returns the first index at which a given element can be found in the array, or -1 if not present.

Write the following code inside the app.js file.

const unique = (value, index, self) =>  return self.indexOf(value) === index > const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.filter(unique) console.log(uniqueAges)

In the above function, we have used the two in-built JavaScript functions.

The array filter() and array indexOf(). We have also used an arrow function, a feature of ES6.

So, in the above code, we filter out each repetitive value using the filter function and pass the unique callback to each array element.

How To Get Distinct Values From Array In Javascript

Method 3: Using the filter() method

The array.filter() function is “used to create a new array from an existing array which satisfies a condition set by the argument function.”

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.filter((x, i, a) => a.indexOf(x) == i) console.log(uniqueAges)

Method 4: Using a set and spread operator

In ES6, the code is much simpler. For example, the code snippet below utilizes the Set object to store the collection of unique values; then, we used the spread operator to construct the new Array.

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = [. new Set(ages)] console.log(uniqueAges)

The constructor of the set takes an iterable object, like an Array, and the spread operator transform the group back into an Array.

The output is the following.

Get Unique Values using Javascript Set

Method 5: Using Set and Array from a method

Use the Set and array from() method to get unique values. It will eliminate duplicate values from an array.

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const result = Array.from(new Set(ages)); console.log(result)

It will give us the same output.

Method 6: Defining our own Array Unique Prototype

We can also define the prototype that can give us the unique value of the Array. Our prototype function will be the following.

Array.prototype.unique = function()  var arr = []; for(var i = 0; i < this.length; i++)  if(!arr.includes(this[i]))  arr.push(this[i]); > > return arr; >

Call the Array Unique function on an array and see the output.

Array.prototype.unique = function()  let arr = []; for(let i = 0; i < this.length; i++)  if(!arr.includes(this[i]))  arr.push(this[i]); > > return arr; > const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = ages.unique() console.log(uniqueAges)

Define our own Array Unique Prototype

2 thoughts on “How to Get All Unique Values from Array in JavaScript”

This gives the answer 2. But how can I avoid “converting” 2D points to a string?
[…new Set([[0, 0], [0, 0], [1, 0]].map(_ => _.join(‘:’)))].length Thanks Reply

Amazing article. after a long search i got this and the various ways of getting the unique values is really interesting
I have one requirement where i have to get unique values from a json array. Each array element has multiple attributes. let us say there are 4 attributes in an element. i want to get unique elements based on attribute 2. eg. the json data is:
“dept”:’HR’, “role”:Manager,”name”:’Moorthi’;
“dept”:’HR’, “role”:Manager,”name”:’Ramesh’;
“dept”:’HR’, “role”:Recruiter,”name”:’Suresh’;
“dept”:’Finance’, “role”:Manager,”name”:’Krunal’;
“dept”:’Finance’, “role”:Auditor,”name”:’Sachin’;
“dept”:’Finance’, “role”:Auditor,”name”:’Ashwin’; I want to get depts as ‘HR’, ‘Finance’ and also if the Dept is HR then the roles in that are like ‘Manager’ and ‘Recruiter’. Any help in this regard is appreciated. Thanks in advance for the help Reply

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Unique array values in JavaScript

We can write a simple function to help us. We’ll use it as a callback for the Array.prototype.every() and Array.prototype.filter() methods.

The callback function for the every() and filter() methods accepts up to three arguments, in the following order:

  1. The current value in the array
  2. The index of the current value in the array
  3. The array itself

We need to check that the first index of the value is equal to the last index of the value. If so, the value is unique. Otherwise, it’s a duplicate.

function isUnique(value, index, array)  
return array.indexOf(value) === array.lastIndexOf(value);
>

Check if every value is unique

The following is an array of fruits. The string ‘apple’ appears twice.

const fruits = [ 'apple', 'apple', 'banana', 'pear' ];

To check if every fruit is unique, we can pass our isUnique() function to the Array.prototype.every() method:

const fruitsAreUnique = fruits.every(isUnique);
console.log(fruitsAreUnique); // false

In this example, the every() method returns false . This is because there are two occurrences of the string ‘apple’ , so not every fruit is unique.

Filter unique values

To remove fruits that appear more than once, we pass our isUnique() function to the Array.prototype.filter() method:

const uniqueFruits = fruits.filter(isUnique);
console.log(uniqueFruits); // [ 'banana', 'pear' ]

In this example, the filter() method removes both occurrences of the string ‘apple’ from the array. Because it appeared twice, it wasn’t unique.

Remove duplicate values

We might just want to remove duplicate fruits from our array, such that we’re still left with one of each fruit. We can easily do this with a Set .

We can pass our fruits array into the Set() constructor to create a Set —a collection of unique values—from the array. Then we can use the spread operator ( . ) to turn the Set back into an array.

const oneFruitEach = [ . new Set(fruits) ];
console.log(oneFruitEach); // [ 'apple', 'banana', 'pear' ]

If you prefer, you can use the Array.from() method:

const oneFruitEach = Array.from(new Set(fruits));
console.log(oneFruitEach); // [ 'apple', 'banana', 'pear' ]

My friend Chris Ferdinandi has a helper function for this: dedupe.js.

Summary

  1. We can use the Array.prototype.every() method to check if every value in an array is unique.
  2. We can use the Array.prototype.filter() method to filter an array such that it only contains unique values.
  3. We can use a Set to remove duplicate values from an array.

👋 Got questions or comments? Email me at kieran@barker.codes.

Copyright © 2023 Kieran Barker. Proudly built with Eleventy and hosted by Netlify.

Источник

Оцените статью