Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 903
Kamalakannan J Avatar asked Sep 12 '15 20:09

Kamalakannan J


People also ask

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.

What's the difference between array splice () and array slice () methods?

The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.

Is splice only for arrays?

JavaScript arrays have a push() function that lets you add elements to the end of the array, and an unshift() function that lets you add elements to the beginning of the array. The splice() function is the only native array function that lets you add elements to the middle of an array.

How do you replace an element in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.


1 Answers

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");

like image 169
josh Avatar answered Oct 09 '22 08:10

josh