takeaway

In front-end development, we often encounter the problem of removing duplicate data from arrays, which is called array deduplication. There are many solutions in the community, such as double-layer for loops, indexOf + Filter, Set, etc. Some also consider {},[], whether NaN is repeated, and performance problems caused by the deduplication of tens of millions of data. However, in a real business development scenario, Most of the situations we encounter are how to remove duplicate data of the same type with a small amount of data. Therefore, this article only lists several common and simple ways to remove duplicate data from the perspective of business scenarios. If you have better ideas, welcome to make a decision in the comment area.

Array decrement (same basic type)

1. Use Set and array. from

2. Use array. filter and array. indexOf

3. Use array. reduce and array. includes

Array objects are deduplicated

As the name implies, the items in the array are no longer basic types, and in a real business development scenario, we need to remove duplicate items based on the properties specified by the object.

1. The key of an object cannot be repeated

2. The use ofMapThe key of is not repeatable

Array adds non-repeatable items

The following picture is the search history list of QQ Music. Whenever a user enters a new keyword, it will be added to the first place in the history list. If there is a repetition, the old one needs to be deleted. In fact, this is also an array object deduplication problem, the solution idea is very simple, directly filter out the old duplicate items, the new item in the first place.