Today, I came across a SO question to replace a matching object inside array of objects.
To do so, they are finding the index of the matching object inside 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 like this,
users.splice(idx, 1, {user: "Gowtham"})
but why not,
users[idx] = {user: "Gowtham"};
Now my question is, Is there any reason, not to do so or to use splice() ?
Because it is so simple to use array[index] = 'something';
. Isn't it ?
array[index]
is faster thanArray.splice()
: jsperf.com/array-index-vs-splice. But your mileage may vary depending on the size of the array, perhaps?.splice()
will act more like.push()
ifidx
is beyond the.length
of the array, whereas index assignment would extend the array's length.