Javascript: replace directly with index vs Array.splice ()

Today I came across a SO question to replace the corresponding object inside an array of objects.

To do this, they find the index of the corresponding object inside the array of objects using lodash .

var users = [{user: "Kamal"}, {user: "Vivek"}, {user: "Guna"}] var idx = _.findIndex(users, {user: "Vivek"}); // returns 1 

Now they used splice () to replace as follows:

 users.splice(idx, 1, {user: "Gowtham"}) 

but why not

 users[idx] = {user: "Gowtham"}; 

Now my question is: is there any reason rather than using or splice () ?

Because it is so simple to use array[index] = 'something'; . Is not it?

+6
source share
1 answer

The only reasons they can do are:

  • they also want to get the previous value
  • they want to "smartly" handle the case where idx == -1, replacing the last element in the array, instead of putting it at -1, because splice will handle negative integers. (this does not look like it will match the use case you described)

in most cases arr[i] = "value"; will be better than arr.splice(i, 1, "value");

+2
source

All Articles