Javascript Array Manipulation With Sets
CP
Posted on April 18, 2020
Array manipulation with Sets
[...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
), []);
💖 💪 🙅 🚩
CP
Posted on April 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
getvm Mastering Web Development: A Comprehensive Collection of Free Online Tutorials
September 1, 2024