The new Set de-reuse method in js

ES6 provides a new data structure, Set, which is similar to an array, but the values of the members are unique and there are no duplicate values; Set itself is a constructor that generates the Set data structure.

Array de-duplication

const arr = [3,5,2,2,5,5]
const unique = [...new Set(arr)]

The Array.from method converts Set structures into arrays. We can specifically write functions that use a de-duplication.

function unique(arr){
  return Array.from(new Set(arr))
}
unique([1,,1,2,2,3,3])

Character de-duplication

In addition, Set is so powerful that it is easy to implement Union, Intersect, and Difference using Set.

let a = new Set([1,2,3])
let b = new Set([4,3,2])
// and set
let union = new Set([...a, ...b])
// Intersection
let intersect = new Set([...a].filter(x => b.has(x)))
// Difference set
let diff = new Set([...a].filter(x => !b.has(x)))
Set {1}

Leave a Reply