Array deduplication

Let’s look at the code first:

const data = [
  {     id: 1,     name: 'zhangsan'   },   {     id: 2,     name: 'lisi'   },   {     id: 1,     name: 'zhangsan'   },   {     id: 3,     name: 'zhaoliu'   } ];















const uniqueData = Array.from(new Set(data.map(item => 
// In addition, you can also use the id directly here. It does not have to be serialized
JSON.stringify(item)))).map(item => JSON .parse(item));


console.log(uniqueData);
// Output: [{ id: 1, name: 'zhangsan' }, { id: 2, name: 'lisi' }, { id: 3, name: 'zhaoliu' }]
 

answer question:

new Set(data.map(item => 

What does JSON.stringify(item))) do?

answer:

This code is used to datadeduplicate elements in an array while retaining the original order. The specific explanation is as follows:

  1. data.map(item => JSON.stringify(item)): This is an array mapping operation that converts  data each element of the array into its string representation. This is to ensure the accuracy of the comparison, because the Set data structure uses the strict equality operator (===) to determine whether elements are equal.
  2. new Set(...): Create a new Set object by passing in the mapped array. Set is a collection without duplicate values, containing only unique elements.
  3. The final return is a Set object containing no duplicate elements.

The function of this code can be understood as deduplicating datathe elements in the array and returning the deduplicated result.

Therefore, each item must be turned into a string because it must be judged accurately.

Guess you like

Origin blog.csdn.net/kuang_nu/article/details/133203203