Skip to content

Instantly share code, notes, and snippets.

@eks1985
Last active September 21, 2016 14:03
Show Gist options
  • Save eks1985/1d37be52c526f57b338b8ebfaf467a73 to your computer and use it in GitHub Desktop.
Save eks1985/1d37be52c526f57b338b8ebfaf467a73 to your computer and use it in GitHub Desktop.
Redux

Methods not mutating data

Add element to array

concat()

const list = [0, 1];
const result = list.concat(2);
console.log('result', result);
//[0, 1, 2]
console.log('list', list);
//[0, 1]

ES6 analog - spread operator

const list = [0, 1];
const result = [...list, 2];
console.log('result', result);
//[0, 1, 2]
console.log('list', list);
//[0, 1]

Remove element from array

slice()

const list = [0, 1, 2];
const index = 1;
var result = list
  .slice(0, index)
  .concat(list.slice(index + 1));
console.log(result);
//[0, 2]

ES6 analog - spread operator

const list = [0, 1, 2];
const index = 1;
result = [
  ...list.slice(0, index),
  ...list.slice(index + 1)
]
console.log(result);
//[0, 2]

Modify array element

const list = [0, 1, 2];
const index = 1;
result = [
  ...list.slice(0, index),
  list[index] + 1,
  ...list.slice(index + 1)
]
console.log(result);
//[0, 2, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment