Last active
May 12, 2018 20:50
-
-
Save iohcidnal/d794cd9c109ed2454ed7a8bd16e1f201 to your computer and use it in GitHub Desktop.
Updating element in array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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