Javascript unique elements in array

Javascript: Get unique values in an array

While working in javascript arrays, we often encounter a situation where we need to pull the unique values from an array. This article will see different ways to extract unique values into a separate array using various example illustrations.

Table of Contents:

Get unique values from an array using filters

Javascript’s filter() metho d returns a new array consisting of all the elements that pass the test implemented by the provided function.

Get the unique values from array [“Hello”, “This”, “Is”,”Language”,”This”, “Is” ]

Frequently Asked:

function getUniqueArray(_array) < // in the newArray get only the elements which pass the test implemented by the filter function. // the test is to check if the element's index is same as the index passed in the argument. let newArray = _array.filter((element, index, array) =>array.indexOf(element) === index); return newArray > let myArray = ["Hello", "This", "Is","Language","This", "Is" ]; console.log(getUniqueArray(myArray));

Explanation:-

  • Here, the filter()method is applied to all elements of the array.
  • In the method filter(element, index, array), the index of each element(first argument) is compared with the index(second argument) of the array(third argument).
  • A new array is created for the elements of equal matches.
Читайте также:  Fillna python что это

Get unique values from an array using SET

Javascript’s Set is to store unique values .

Get the unique values from array [“Hello”, “This”, “Is”,”Language”,”This”, “Is” ]

function getUniqueArray(_array) < //store the _array elements in the Set and then create a newArray from this Set let newArray =[. new Set(_array)]; return newArray >let myArray = ["Hello", "This", "Is","Language","This", "Is" ]; console.log(getUniqueArray(myArray));

Explanation:-

  • In the above code, the origi nal array myArray elements are stored in a Set.
  • A new array newArrray is then created, taking all the elements of the Set created. Since the Set contains unique values, the newly created array has unique values only.

Get unique values from an array using Object

Get the unique values from array [“Hello”, “This”, “Is”,”Language”,”This”, “Is” ]

function getUniqueArray(_array) < var obj = <>; var uniqueArray = []; for (var i = 0; i < _array.length; i++) < if (obj[_array[i]] == undefined) // add the array elements to object , where the element is key and the same element is value // keys of the object can only have unique values < obj[_array[i]] = i; // add the keys of the object to a new array as elements of the array uniqueArray.push(_array[i]); >> return uniqueArray; > let myArray = ["Hello", "This", "Is","Language","This", "Is" ]; console.log(getUniqueArray(myArray));

Explanation:-

  • In the above code, the original array myArray elements are stored in an Object where each array element is passed as a key, and the same element is passed as the value of the object key-value pairs.
  • A new array uniqueArray is then created from all the keys of the object created.
  • Since the keys of an object are unique, the newly created array has unique values only.

Get unique values from an array using iteration

Get the unique values from array [“Hello”, “This”, “Is”,”Language”,”This”, “Is” ]

function containsElement(_array,_value) < for (var i = 0; i < _array.length; i++) < // check if new array already contains the element if (_array[i] === _value) return true; >return false; >; function getUniqueArray(_array) < var newArray = []; for (var i = 0; i < _array.length; i++) < if (!containsElement(newArray,_array[i])) < // if the element is not found in the newArray push it. newArray.push(_array[i]); >> return newArray; > let myArray = ["Hello", "This", "Is","Language","This", "Is" ]; console.log(getUniqueArray(myArray));

Explanation:-

  • In the above code, two functions are created containsElement() and getUniqueArray().
  • In function getUniqueArray() , a new array newArray[] is created, all the elements of the array are traversed in afor loop. The method containsElement(newArray,_array[i]) is called at every traversal where newArray and element of the array are passed as arguments. The containsElement() checks if the passed element is already present in the array. If yes, then do not push the element in the newArray. Else push the element to the newArray.

I hope this article helped you to get unique values from a javascript array. Good Luck .

Share your love

Leave a Comment Cancel Reply

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

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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.

Источник

Three methods to get unique values from arrays in ES6.

This article was originally published on everistus.me There are several ways and several algorithms that you can easily implement to retrieve unique element in an array in JavaScript. In this article, we will discuss three of those ways. This is the first article in The JavaScript Snippet Series. It is accompanied by a video.

Using Set

In ES6, a Set is a collection of values. The values in a set are unique in the Set’s collection. Using this property of a Set, we can pass an array into a Set and because each value in the Set has to be unique, the value equality will be checked. This means the Set will only retain unique values. We can, therefore, using the spread operator return a new array of unique values.

const arr = [2019, 2020, 2019, 2018, 2020, 2021, 2030, 2020, 2019]; // Using sets const useSet = arr =>  return [. new Set(arr)]; >; console.log(result); 

Screen Shot 2020-03-30 at 5.04.56 AM.png

This will return a new array with only unique elements like we wanted.

Using Array.filter

The next method we will be using is using ES6 Array.filter function. The Array.filter function takes a callback whose first parameter is the current element in the operation. It also takes an optional index parameter and the array itself. Combining these, we can use Array.filter to ensure only unique element are returned in the array

// Using Array.filter const useFilter = arr =>  return arr.filter((value, index, self) =>  return self.indexOf(value) === index; >); >; const result = useFilter(arr); 

Screen Shot 2020-03-30 at 5.04.56 AM.png

This will give us the same result as before:

Using Iteration

The last method we will consider is using a for. of loop to iterate through the array and keep only unique elements in a new array.

// Using iteration const useIteration = arr =>  const map = []; for (let value of arr)  if (map.indexOf(value) === -1)  map.push(value); > > return map; >; const result = useIteration(arr); 

Screen Shot 2020-03-30 at 5.04.56 AM.png

We create a new array, simply loop through the initial array and then if the current element is not in the new array, we push it into the new array else, we leave it out. At the end of the iteration, we return the new array that contains unique values. It also produces the correct result for us That is three simple ways to return unique values in an array in ES6. Note: We did not discuss the time and space complexity using these simple algorithms. If you would like to discuss it, why not add a comment either on the youtube page or on the comment below. We will be discussing array sorting in the next episode of JavaScript Snippet Series. Hope to see you back here soon.

Источник

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