Skip to content

Instantly share code, notes, and snippets.

@iohcidnal
Last active May 12, 2018 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iohcidnal/d794cd9c109ed2454ed7a8bd16e1f201 to your computer and use it in GitHub Desktop.
Save iohcidnal/d794cd9c109ed2454ed7a8bd16e1f201 to your computer and use it in GitHub Desktop.
Updating element in array
const arr = [
{ id: 0, name: 'john'},
{ id: 1, name: 'mark' },
{ id: 2, name: 'luke' },
{ id: 3, name: 'peter' },
];
const newPerson = {id: 2, name: 'newPerson'};
const index = arr.findIndex(val => val.id === newPerson.id);
console.log(index);
const slice1 = [...arr.slice(0, index)];
console.log(slice1);
const slice2 = [...arr.slice(index + 1)];
console.log(slice2);
const newArr = [
...arr.slice(0, index),
newPerson,
...arr.slice(index + 1)
];
console.log(arr);
console.log(newArr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment