Last active
June 29, 2017 07:08
-
-
Save iuliaL/1b4f38511fa4ddfc5e8f8491f75fc716 to your computer and use it in GitHub Desktop.
remove item from array in a declarative way, avoiding array mutations
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
/* | |
remove item from array in a declarative way, | |
avoiding array mutations | |
Instead of splicing | |
*/ | |
// 1. use Array.filter | |
const removeItem = (list,index) => list.filter((item,i) => index !== i) | |
removeItem( [0,10,20], 1) | |
// => [0, 20] | |
// 2. use Array.slice | |
const removeItem = (list,index) => list.slice(0,index).concat(list.slice(index+1)); | |
// (copy the previous and next parts of the index into a new array) | |
//using ...array spread es6 | |
const removeItem = (list,index) => [ ...list.slice(0,index), ...list.slice(index+1) ]; | |
removeItem( [0,10,20], 1) | |
// => [0, 20] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment