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 ?
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 ?
-
2
It is true that using
array[index]
is faster thanArray.splice()
: jsperf./array-index-vs-splice. But your mileage may vary depending on the size of the array, perhaps? – Terry Commented Sep 12, 2015 at 20:46 - 1 Unless you want to get the removed value (which isn't being done here), index assignment would make more sense and be most likely faster. – user1106925 Commented Sep 12, 2015 at 20:46
-
1
Ah, one difference is that
.splice()
will act more like.push()
ifidx
is beyond the.length
of the array, whereas index assignment would extend the array's length. – user1106925 Commented Sep 12, 2015 at 20:50
1 Answer
Reset to default 13The only reasons they might do this are:
- they want to also get the previous value
- they want to 'cleverly' handle the case where idx == -1 by replacing the last element in the array, rather than putting it at -1, because splice will treat negative integers specially. (this doesn't seem like it would fit the use-case you described)
in most cases, arr[i] = "value";
will be better than arr.splice(i, 1, "value");