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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With