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

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