DEV Community

CP
CP

Posted on • Edited on

1 1

Javascript Array Manipulation With Sets

Array manipulation with Sets

Samples on Codepen

[...new Set(arr)] // unique array
[...new Set(arr)].sort() // unique array sorted

// Union (deduped):
const union = (a1, a2) => [...new Set(a1.concat(a2))];

// Union arbitrary number of arrays:
[a1, a2, a3, ...].reduce((total, arr) => union(total, arr), []);

// Intersection (deduped):
const intersection = (a1, a2) => [...new Set(a1.filter(x => a2.includes(x)))];

// flatten array with any depth
const flat = (arr) => arr.reduce((a, value) => a.concat(
  Array.isArray(value) ? flat(value) : value
), []);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
calvinpak profile image
CP

Note on unions:
[...new Set(a1, a2))] works for same type, failed with [1], ['x'], updated to use concat instead.

Use Set only to dedupe, use Array for manipulation.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay