Skip to content

Instantly share code, notes, and snippets.

@knoonrx
Last active May 1, 2019 19:42
Show Gist options
  • Save knoonrx/f77d77235bb1f33ec5f874bbff699797 to your computer and use it in GitHub Desktop.
Save knoonrx/f77d77235bb1f33ec5f874bbff699797 to your computer and use it in GitHub Desktop.
Use the spread operator to remove duplicates items and to sort a array of numbers and objects, without destruct the original array.
// define the array of numbers and objects
const array = [{
nome: 'joão',
idade: 14
},{
nome: 'joão',
idade: 14
},7,9,8,5,15,3,9,8,6];
// remove duplicate numbers only, items of type object are not affected
let array1 = [... new Set(array)]
// remove duplicate numbers and sort then, but items of type object are not affected
let array2 = [... new Set(array)].sort((a,b) => a - b)
// remove duplicate numbers and objects and sorting them too, in this case the items of type object are affected also.
let array3 =[... new Set(array.map(o => JSON.stringify(o) ))].sort((a,b) => a - b).map(i => JSON.parse(i))
console.log(array, array1, array2, array3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment