15

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 ?

Community
  • 1
  • 1
Kamalakannan J
  • 2,818
  • 3
  • 23
  • 51
  • 2
    It is true that using `array[index]` is faster than `Array.splice()`: http://jsperf.com/array-index-vs-splice. But your mileage may vary depending on the size of the array, perhaps? – Terry Sep 12 '15 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. –  Sep 12 '15 at 20:46
  • 1
    Ah, one difference is that `.splice()` will act more like `.push()` if `idx` is beyond the `.length` of the array, whereas index assignment would extend the array's length. –  Sep 12 '15 at 20:50

1 Answers1

11

The only reasons they might do this are:

  1. they want to also get the previous value
  2. 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");

josh
  • 364
  • 4
  • 7