Remove Duplicates from Array – JavaScript TypeScript ES6

In this post, we will learn how to remove duplicate values from a JavaScript array. We will be discussing various ways to get unique values out of Arrays using the latest ES6 TypeScript method.

JavaScript has a number of methods to operate on Arrays, further, we will discuss the best combination of these different types of JavaScript functions to return unique or dups free Arrays.

Before going further, let’s have sample Arrays that will be having numbers and strings as shown below:

Number Arrays:

let numArr = [ 53, 8, 14, 7, 96, 23, 5, 23, 85, 8, 99, 13, 304];

String Arrays:

let strArr = [ 'aaa', 'bbb', 'ccc', 'aa', 'aaa', 'c', 'bbb']; 

How to remove duplicates from simple Array using TypeScript ES6?

In ECMAScript 6 we can easily use advanced javaScript methods to have complex login in few lines of code. In Angular, we use TypeScript which is compatible with most of the latest browsers.

Let’s have a look at the quickest and easiest way to fetch unique values from an Array of Numbers or Strings.

let numArr = [ 53, 8, 14, 12, 1, 5, 5, 7, 96, 23, 5, 23, 85, 8, 99, 13, 304]; 

const filteredNumArray = numArr.filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredNumArray); // [53, 8, 14, 12, 1, 5, 7, 96, 23, 85, 99, 13, 304]


let strArr = [ 'aaa', 'bbb', 'ccc', 'aa', 'aaa', 'c', 'bbb']; 

const filteredStrArray = strArr.filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredStrArray); //  ["aaa", "bbb", "ccc", "aa", "c"]

 

You can also re-write the above filter inside a function as shown below:

let numArr = [ 53, 8, 14, 12, 1, 5, 5, 7, 96, 23, 5, 23, 85, 8, 99, 13, 304];
let strArr = [ 'aaa', 'bbb', 'ccc', 'aa', 'aaa', 'c', 'bbb']; 

function returnUnique(arr){
    return arr.filter((value, index, self) => self.indexOf(value) === index);
}
console.log(returnUnique(numArr)); // [53, 8, 14, 12, 1, 5, 7, 96, 23, 85, 99, 13, 304]
console.log(returnUnique(strArr)); // ["aaa", "bbb", "ccc", "aa", "c"]

 

Above, we have used the filter and indexOf methods. The filter() method iterates over each value and matches if the value exists on the previous index using the indexOf methods.

These three arguments for the filter method,

self : Returns a complete array.

index: Index of the current item.

value: Value of current item at index.

 

To sum up, here we discussed a clean and quick way of removing duplicate values from an Array.

Leave a Reply

Your email address will not be published. Required fields are marked *