AppDividend
Latest Code Tutorials

JavaScript Unique Array: How To Use Array.Filter() Method

If you are looking for a solution for getting a unique javascript array, your answer is the […new Set(arr)] method. The triple dot (…) is the spread operator. Primitive values in 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 how I can get a list of unique values in Array.

Javascript Unique Array Example

To find a unique array and remove all the duplicates from the array, you can use one following ways.

  1. Use new ES6 feature: […new Set( [1, 1, 2] )];
  2. Use object { } to prevent duplicates
  3. Use a helper array [ ]
  4. Use filter + indexOf
  5. Define our own array unique prototype

If you have an array of dates, then you need some more customized methods. 

Get Unique array values using filter + indexOf

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 the 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 the 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.

See the output

How To Get Distinct Values From Array In Javascript

ES6 Javascript filter() method

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 array values using a 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 the 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 the set takes an iterable object, like Array, and the spread operator  transform the set back into an Array.

The output is the following.

Get Unique Values using Javascript Set

Distinct array values using Set and Array from a 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.

Get unique array values using array[] helper

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 the 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.

See the final code.

// 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)

See the output.

Define our own Array Unique Prototype

Conclusion

Finally, If you want to get a distinct value in the Javascript array with performance improvement, use the array = […new Set(array)] method. It does not make the process slow.

If you use filter() + indexOf() method then performance might get slow in the large amount of data.

See also

Javascript array map()

Javascript array foreach()

Javascript array contains

2 Comments
  1. Dominic Rose says

    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

  2. Moorthi says

    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

Leave A Reply

Your email address will not be published.

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