debarchito
debarchito

Reputation: 1335

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

Upvotes: 5

Views: 11341

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50664

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

Upvotes: 3

Steven B.
Steven B.

Reputation: 9362

If you want to call it upon the array you can add a prototype function. I'd use an object as the argument though and each key would correspond to an index.

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

Array.prototype.update = function(args) {
  for (var key in args) {
    this[key] = args[key];
  }
  return this;
};

a.update({ 0:"1", 2:"3", 3:"4" })
console.log(a)

Upvotes: 3

Anthony
Anthony

Reputation: 6482

You could do it like this, using the key value pairs of an object parameter to update the array in the first parameter.

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

const update = (arr, changes) => {
  for(k in changes) {
    arr[k] = changes[k];
  }
};

update(a, { 0: '1', 2: '3', 3: '4' });

console.log(a);

Upvotes: 2

Related Questions