Skip to content

Instantly share code, notes, and snippets.

@iuliaL
Last active June 29, 2017 07:08
Show Gist options
  • Save iuliaL/1b4f38511fa4ddfc5e8f8491f75fc716 to your computer and use it in GitHub Desktop.
Save iuliaL/1b4f38511fa4ddfc5e8f8491f75fc716 to your computer and use it in GitHub Desktop.
remove item from array in a declarative way, avoiding array mutations
/*
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