5

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

2
  • 2
    Have you considered using a for or foreach loop? Commented Oct 26, 2019 at 3:10
  • 2
    This should help: stackoverflow.com/questions/1374126/… Commented Oct 26, 2019 at 3:12

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.