Created
October 18, 2019 08:55
-
-
Save munkacsitomi/21f3e29a378eb739a5bb74216e5889d8 to your computer and use it in GitHub Desktop.
Rest and Spread operator examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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