Skip to content

Latest commit

 

History

History
76 lines (67 loc) · 1.25 KB

arrayModifications.md

File metadata and controls

76 lines (67 loc) · 1.25 KB

#Make changes to arrays without mutating them:

var arr = [1, 2, 3];
var index = 1;

1. Add a new element to the array:

####Mutable:

arr.push(4) 
console.log(arr) // arr = [1,2,3,4]

####Immutable solution:

console.log(        
    arr.concat([4])         
); 
// [1,2,3,4]

Using the ES6 Spread operator:

console.log(
    [...arr,4]             
); 
// [1,2,3,4]

2. Remove an element in the array:

####Mutable:

arr.splice(1,1);
console.log(arr) // arr = [1,3]

#####Immutable solution:

console.log(       
    arr.slice(0,index).concat(arr.slice(index+1))      
); 
// [1,3]

Using the ES6 Spread operator:

console.log(       
    [...arr.slice(0,index), ...list.slice(index+1)]       
); 
// [1,3]

3. Add 1 to the second element:

Mutable:

console.log(       
   arr[index]++     
); 
// [1,3,3]

#####Immutable solution:

console.log(       
   arr.slice(0, index).concat([arr[index]+1]).concat(arr.slice(index+1))
); 
// [1,3,3]

Using the ES6 Spread operator:

console.log(       
   [...arr.slice(0, index), arr[index]+1, ...arr.slice(index+1)]
); 
// [1,3,3]