Register Login

Get all Unique Values in a JavaScript Array

Updated Feb 12, 2024

All programmers are familiar with working with arrays in JavaScript. An array is a single linear data structure; which contains a bunch of

different data-type elements. But implementing arrays can be more efficient if users know how to get all the unique elements in a JS array. Make sure all grab all the methods that allow users to filter and remove duplicates from the array. This article will highlight all these methods with their respective code examples and explanations.

Method 1: The filter() method

Example: Using the filter() and indexOf() methods

Users can use this method to create a new array from the given JS array, which will contain only those elements from the original array that satisfies the provided condition specified by the argument function.

Syntax:

array.filter( function(currentValue, index, arr), thisValue )

The following are the parameters used in the method:

  • currentValue: The currentValue parameter holds the value of the current element.
  • index: This parameter specifies the index of the current element that the method will process.
  • arr: The JS method will get called in this array parameter.
  • thisValue: The method will use the value of thisValue parameter when executing the argument function.

Code Snippet:

let a = [1, 2, 3, 4, 3, 6, 8, 4, 9, 7, 8, 5, 2, 0, 7, 3]
let h = [];
function using_filter(b) {
	let h = b.filter(function (val, index, arr) {
		return index == arr.indexOf(val);
	});
	return h;
}
console.log(using_filter(a));

Output:

Run Code

Explanation:

In this example, we used the filter() method to remove all the duplicate elements from the initialized array "a." Then, we used a helper array "h" that finds the elements from the given array.

We initialized a function using_filter with a parameter "b" that executes the filter() and indexOf() methods. The indexOf() method will return the index of the first elements of the array and the filter() method returns only those elements that pass the given condition.

Example: Using sort() with filter() methods

The sort() method helps users sort the elements of an array in place, returning the reference to the original array. By default, the sort() method will sort the array elements in ascending order.

Code Snippet:

var emp_names = ["c", "a", "b", "a", "c", "g", "d", "b"];
var sorted_list = emp_names.sort();
const res = sorted_list.filter((e, i) => sorted_list[i] != sorted_list[i+1]);
console.log(res);

Output:

Run Code

Example: Using the reduce() and filter() method

The reduce() method reduces the array into a single value and then runs the reducer function for the array element. The following code example will explain how it works:

Code Snippet:

let array = [{ ID: '9681'}, { ID: '5779'}, { ID: '9699'}, { ID: '9681'}, { ID: '9681'}, { ID: '4266'}, { ID: '6542'}, { ID: '8625'}];
array = array.reduce((acc, cur) => [
  ...acc.filter((obj) => obj.ID !== cur.ID), cur
], []);
console.log(array);

Output:

Run Code

Explanation:

We have initialized an array with objects having key-value pair. The reduce() method first reduced the array into single elements, and the filter() method matched the ID values. Then, the filter() method returned only those elements that pass the given condition.

Method 2: Using for loop

In this method, we will check each value of the original array with each value of the output array. Here, we will remove all the duplicate values from the array.

Code Snippet:

let a = ["Bishal", "Ashish", "Carron", "Bishal", "Eliza", "Deizzi", "Eliza", "Bishal"];
let b = [];
let c = 0;
let starting = false;
for (let i = 0; i < a.length; i++) {
	for (let j = 0; j < b.length; j++) {
		if (a[i] == b[j]) {
			starting = true;
		}
	}
	c++;
	if (c == 1 && starting == false) {
		b.push(a[i]);
	}
	starting = false;
	c = 0;
}
console.log(b);

Output:

Run Code

Explanation:

In the for loop method, we iterated over the elements of the array, and the helper array returned a new Set of elements without duplicate values. Look at the output and check all th elements are unique.

If the current elements do not exist in the final array "b" with unique values, users must add the element to the final array.

Method 3: Using the Set() method

In JavaScript, users can use a Set that specifies a collection of unique elements. Here, users cannot declare repeated elements inside the "Set." Users can iterate the elements of a Set in ES6 in the insertion order.

Also, the JS Set allows users to store any data type element, despite primitive or objects.

Code Snippet:

let a = ["Python", "C++", "JavaScript", "C++", "Java", "HTML", "Java", "CSS", "Python"];
let b = [];
function using_Set(array) {
	let b = Array.from(new Set(array))
	return b
}
console.log(using_Set(a));

Output:

Run Code

Explanation:

Using the native object Set of ES6, we stored and returned some unique elements. First, we initialized a function "using_Set" and passed the array having duplicate elements into the Set() object.

The helper array will contain all the unique elements filtered in the function.

Example: More easy structure of Set

The constructor of Set accepts the iterable object, here an Array, and the spread operator "..." to change the Set object back into the original array, filtering all the duplicate elements.

Code Snippet:

var a = [1, 2, 3, 4, 5, 3, 1, 5, 2, 3, 6];
var b = [...new Set(a)];
console.log(b);

Output:

Run Code

Method 4: Using the Array.includes() method

The includes() method returns true if the JS array holds a specific value. Else it returns false if it does not find the value. It is case-sensitive.

Code Snippet:

var a = [0, 1, 3, 5, "a", "1", 2, 4, "B", 1, 3]
console.log( 
  a.filter((val,index) => !a.includes(val,index+1))
)

Output:

Run Code

Explanation:

The includes() method with the second parameter "fromIndex" is for searching every iteration of the filter callback method. The search started from the current [current index] + 1. The includes() method guarantees not to include currently filtered elements in the returned array.

Conclusion

We hope this article has given a crisp idea of different methods available in JavaScript to filter an array uniquely. All the above methods are efficient in specific scenarios, returning a JS array of unique elements.

The article covered filter(), filter() with sort(), filter() with reduce(), Set(), includes(), and for loop techniques.


×