Implementing Unique (removing duplicates from an array) in JavaScript

この記事は約5分で読めます。
スポンサーリンク

Things I want to do

This explains how to implement Unique (removing duplicates from an array) in JavaScript.

I will introduce two methods using filter and set.

スポンサーリンク

implementation

The man used the implementation

The Filter function is used to remove duplicate elements.

The `findIndex()` method searches for an element identical to the one being checked, and if an element with a smaller index is found, it is selected for deletion. (`arr.findIndex((ele) => element == ele) == index)`

(You might be wondering why the element with the larger index isn’t deleted, but it’s not a problem because it’s deleted when the element with the larger index is checked. In the example below, the first ‘element0’ is not deleted, but the second ‘element0’ is.)

const elements = ["element0", "element0", "element1", "element2", "element3", "element4","element1","element1","element2"];

const result = elements.filter((element, index, arr) => 
  arr.findIndex((ele) => element == ele) == index
);

console.log(result);

Result:

Array ["element0", "element1", "element2", "element3", "element4"]

application

Whether elements are identical is determined by the function to which findIndex is also passed, so they don’t actually need to be the same in the true sense.

The example below shows the results of running Unique(result), which is case-sensitive, and Unique(result), which is case-insensitive.

const elements = ["Element0", "element0", "element1", "element2", "element3", "element4","element1","Element1","element2"];

const result = elements.filter((element, index, arr) => 
  arr.findIndex((ele) => element == ele) == index
);
const result2 = elements.filter((element, index, arr) => 
  arr.findIndex((ele) => element.toUpperCase() == ele.toUpperCase()) == index
);
console.log(result);
console.log(result2);

Result:

 Array ["Element0", "element0", "element1", "element2", "element3", "element4", "Element1"]
 Array ["Element0", "element1", "element2", "element3", "element4"]

Additionally, if you want to check for uniqueness in an array of objects, you can do so using a check like `element.name == ele.name`.

Implementation using Set

Create a Set (similar to an Array, but without duplicate elements) and convert it to an Array.

const elements = ["element0", "element0", "element1", "element2", "element3", "element4","element1","element1","element2"];

console.log([...new Set(elements)]);

Result:

Array ["element0", "element1", "element2", "element3", "element4"]

When implementing Unique using Set, it’s common to convert to an Array using from(), but it’s cleaner to use spread(…) for the conversion.

スポンサーリンク

Result

I was able to implement Unique (removing duplicates from an array) in JavaScript.

スポンサーリンク

Websites I used as references

Set - JavaScript | MDN
Set オブジェクトは、プリミティブ値やオブジェクト参照を問わず、あらゆる型で多数の一意の値を格納することができます。

コメント

タイトルとURLをコピーしました