Skip to content

Instantly share code, notes, and snippets.

@kole
Last active September 11, 2017 19:24
Show Gist options
  • Save kole/82b75549efe2bf9f8cfcecacc282918f to your computer and use it in GitHub Desktop.
Save kole/82b75549efe2bf9f8cfcecacc282918f to your computer and use it in GitHub Desktop.
Unique Arrays in ES2015
// adapted from https://gist.github.com/aherve/741753e1f25e4c87450e6aebe590134b
// more info on Set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
// Get a unique array of numbers
const numbersArr = [4, 1, 2, 1, 1, 2, 1, 3, 4, 1 ]
const uniqNumArr = [...new Set(numbersArr)] // => [ 4, 1, 2, 3 ]
const uniqNumArrSorted = [...new Set(numbersArr)].sort(); // => [ 1, 2, 3, 4 ]
// Get a unique array of strings (unsorted)
const strArr = ['c', 'a', 'b', 'c', 'c', 'c', 'd', 'a'];
const uniqStrArr = [...new Set(strArr)]; // => [ 'c', 'a', 'b', 'd' ]
const uniqStrArrSorted = [...new Set(strArr)].sort(); // => [ 'a', 'b', 'c', 'd' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment