Skip to content

Instantly share code, notes, and snippets.

@ldong
Created April 11, 2016 08:32
Show Gist options
  • Save ldong/71d41599c2c4ce8d75e254372f2b4d1a to your computer and use it in GitHub Desktop.
Save ldong/71d41599c2c4ce8d75e254372f2b4d1a to your computer and use it in GitHub Desktop.
avoid mutation array and object using latest javascript

Array

Remove

list.splice(index, 1);

=>

list
.slice(0, index)
.concat(list.slice(index+1));

=>

[
  ...list.slice(0, index),
  ...list.slice(index+1)
];

Add

list[index]++

=>

list
.slice(0, index)
.concat([list[index]+1])
.concat(list.slice(index+1))

=>

[
  ...list.slice(0, index),
  list[index] + 1,
  ...list.slice(index+1)
];

Object

{
  id: todo.id,
  text: todo.text,
  completed: !todo.completed
}

=>

Object.assign({}, todo, {
  completed: !todo.completed
});

=>

{
  ...todo,
  completed: !todo.completed
}

Reference

  1. Redux: Avoiding Array Mutations with concat(), slice(), and ...spread - js Video Tutorial #free @eggheadio
  2. Redux: Avoiding Object Mutations with Object.assign() and ...spread - js Video Tutorial #free @eggheadio
@ldong
Copy link
Author

ldong commented Apr 11, 2016

  1. Array.prototype.slice() - JavaScript | MDN
  2. Array.prototype.splice() - JavaScript | MDN
  3. Function.prototype.apply() - JavaScript | MDN
  4. Function.prototype.call() - JavaScript | MDN
  5. Array - JavaScript | MDN:

push: add to the end
pop: remove from the end
unshift: remove Apple from the front
shift: add to the front

//remove
array.indexOf(obj);
var removedItem = fruits.splice(pos, 1); // this is how to remove an item

fruits.slice(); // this is how to make a copy

New ES2015 aka ES6

  1. Array.of() - JavaScript | MDN
  2. Array.from() - JavaScript | MDN

@ldong
Copy link
Author

ldong commented Apr 11, 2016

arr = [{a:1}, 2,3];
// output: [ { a: 1 }, 2, 3 ]

arr.indexOf({a:1})
// output: -1

arr.findIndex(function(element, index){
  if (element['a'] === 1){
    return true;
  }
  return false;
});
// output: 0

Note:
Array.prototype.indexOf() is used for primitives, while Array.prototype.findIndex() is used for complex objects

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment