AppDividend
Latest Code Tutorials

How To Get Distinct Values From Array In Javascript

0

In this tutorial, we will see How To Get Distinct Values From Array In Javascript. Primitive values in the JavaScript are immutable values except for objects. Types of primitive values include Null, Undefined, Boolean, Number, Symbol and String. This tutorial also gives you the answer to the How can I get a list of unique values in an array. So see the following example.

Get Distinct Values From Array In Javascript

Write the following code inside the app.js file.

// app.js

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. Javascript Array Filter and Javascript Array Indexof. We have also used an arrow function which is the feature of ES6.

So, actually, in the above code, we filter out each repetitive value using filter function and pass the unique callback to each array item.  The array indexOf() method returns a first index at which the given element can be found in an array, or -1 if it is not present in an array. That way, we filter out the values, and remaining values form an array, and that result array has unique values.

The native method filter will loop through the array and leave only those entries that pass the given callback function unique.

The unique function checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

The output is following.

 

How To Get Distinct Values From Array In Javascript

Above Code Using ES6

We can reduce the above code to only just three lines of code and actual logic to 1 line. See the following code.

// app.js

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)

It will give the same output.

Get Unique Values using Javascript Set

In ES6, the code is much simpler. The code snippet below utilizes the Set object to store the collection of unique values then we have used spread operator to construct the new array. See the following example.

// app.js

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

console.log(uniqueAges)

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

The output is following.

 

Get Unique Values using Javascript Set

Above solution only works for the primitive values. If you have the array of dates, then you need some more customized methods.

Using Set and Array From Method

We can also use the Javascript Set and Javascript Array From method to get unique values. It will eliminate the duplicate values from an array. See the following code.

// app.js

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.

Distinct property values of the array of objects

Let’s get the unique values from an array of objects. See the following code.

// app.js

const students = [
  {
    name: 'Krunal',
    age: 26
  },
  {
    name: 'Ankit',
    age: 25
  },
  {
    name: 'Krunal',
    age: 26
  }
]
const uniqueArr = [... new Set(students.map(data => data.name))]
console.log(uniqueArr)

In the above code, we defined one object with the repeated properties and then we have used the set and use the Javascript Array Map function to form an array with unique values. See the following output.

 

Distinct property values of an array of objects

Define 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 following.

// app.js

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; 
}

Now, call the Javascript Array Unique function on an array and see the output. The final code is following.

// app.js

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)

The output is following.

 

Define our own Array Unique Prototype

Finally, How To Get Distinct Values From Array In Javascript or How To Remove Duplicate Values From Array in Javascript Tutorial is over.

Leave A Reply

Your email address will not be published.

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