Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Created October 18, 2019 08:55
Show Gist options
  • Save munkacsitomi/21f3e29a378eb739a5bb74216e5889d8 to your computer and use it in GitHub Desktop.
Save munkacsitomi/21f3e29a378eb739a5bb74216e5889d8 to your computer and use it in GitHub Desktop.
Rest and Spread operator examples
// Copying an array
let copy = [...arr]
// Creating an array of unique elements
let uniqueElements = [...new Set(arr)];
let elementsStartingWithA = [...new Set(arr)].filter(e => e.startsWith('a'));
// Concatenate arrays
let concat = [...arr1, ...arr2];
// Slicing an array
let [firstElement, ...remainingArray] = arr;
let [, ...remainingArray] = arr;
// Creating a copy of an object (this is not deep copy!)
let copy = {...obj}
// Merging objects
let merge = {...obj1, ...obj2}
// Conditionally adding properties to objects
let conditionalMerge = {...obj1, ...(condition ? obj2 : {})}}
let conditionalMerge = {...{ key1 : 1 }, ...(true ? { key2 : 2 }: {}), ...(false ? { key3 : 3 }: {})}
// Splitting a string to characters
let charactersArray= [...str]
// Destructuring and Rest Operator
let [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment