Created
July 10, 2019 06:46
-
-
Save deleteman/d3db2b3dccc720a89b4ed7e7c1b1902d to your computer and use it in GitHub Desktop.
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
let array1 = [1,2,3,4] | |
//Copying an array | |
let copyArray = [...array1] | |
copyArray.push(4) | |
console.log(array1) | |
console.log(copyArray) | |
/* | |
[ 1, 2, 3, 4 ] | |
[ 1, 2, 3, 4, 4 ] | |
*/ | |
//**WARNING*/ | |
let otherArray = [[1], [2], [3]] | |
copyArray = [...otherArray] | |
copyArray[0][0] = 3 | |
console.log(otherArray) | |
console.log(copyArray) | |
/* | |
Spread does a shallow copy | |
[ [ 3 ], [ 2 ], [ 3 ] ] | |
[ [ 3 ], [ 2 ], [ 3 ] ] | |
*/ | |
//Array concats | |
let array2 = ['a', 'b', 'c'] | |
let result = [...array1, ...array2] | |
console.log(result) | |
//[ 1, 2, 3, 4, 'a', 'b', 'c' ] | |
//**WARNING */ | |
let myString = "hello world" | |
let result2 = [...array1, ...myString] //totally valid but... | |
console.log(result2) | |
//[ 1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' ] | |
result2 = array1.concat(myString) //maybe this is what you really want | |
console.log(result2) | |
//[ 1, 2, 3, 4, 'hello world' ] | |
result2 = [...array1, ...array2, myString] //or this is valid too | |
console.log(result2) | |
//[ 1, 2, 3, 4, 'a', 'b', 'c', 'hello world' ] | |
//Merging objects | |
let myObj1 = { | |
name: "Fernando Doglio", | |
age: 34 | |
} | |
let myObj2 = { | |
name: "Fernando Doglio", | |
age: 35, | |
country: "Uruguay" | |
} | |
let mergedObj = {...myObj1, ...myObj2} | |
console.log(mergedObj) | |
// { name: 'Fernando Doglio', age: 35, country: 'Uruguay' } | |
//Cleaning up repeated elements from an array | |
let myArray3 = [1,2,3,4,4,4,4,2,3,3,4,6] | |
let mySet = new Set(myArray3) | |
myArray3 = [...mySet] | |
console.log(myArray3) | |
//[ 1, 2, 3, 4, 6 ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment