Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update arrays in javascript with index dynamically?

Lets consider an array :

var a = ["one", "two", "three"];

Now, to update the arrays I have to do :

a[0] = "1";
a[1] = "2";
a[2] = "3";

But I, can't repeat this if the array is larger. I want a function with the help of which, I can do like this :

a.update(0, "1", 2, "3", 3, "4"); // => ["1", "two", "3", "4"]

Yes, you saw that with the help of this I added the fourth property, while first and third got updated? So, can this be made? Or there is a better way to perform the task above?

Thanks In Advance

like image 825
Debarchito Avatar asked Jan 25 '23 16:01

Debarchito


1 Answers

You could do this recursively, using destructuring and the rest syntax to grab the index and item at each iteration:

const a = ["one", "two", "three"];

const update = (arr, idx, itm, ...rest) => {
  arr[idx] = itm;
  if(rest.length)
    update(arr, ...rest);
}

update(a, 0, "1", 2, "3", 3, "4")
console.log(a);

Or, you can use a for loop, and skip 2 indexes at a time:

const a = ["one", "two", "three"];

const update = (arr, ...rest) => {
  for(let i = 0; i < rest.length; i+=2) {
    const idx = rest[i];
    const itm = rest[i+1];
    arr[idx] = itm;
  }
}

update(a, 0, "1", 2, "3", 3, "4")
console.log(a);
like image 112
Nick Parsons Avatar answered Jan 28 '23 09:01

Nick Parsons