I have an Array, I would like to add index number of each element after each element inside parentheses, for example milk (0)
.
myArray=['milk', 'bread', 'eggs']
I have an Array, I would like to add index number of each element after each element inside parentheses, for example milk (0)
.
myArray=['milk', 'bread', 'eggs']
I want to replace the existing array.
I was trying to use
for (let i=0; i<myArray.length; i++){
myArray[i]=myArray[i]+'(??)'}
but I couldn’t think of how to put index number of each element into the place of ??.
The index is represented by the variable i, so why not concatenate between the (
and the )
?
Hey @LauraXiaoLiu,
note that replacing variable with new array and updating array in place has practically the same effect, so:
let arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
arr[i] += i;
}
// Is pretty much the same as:
arr = arr.map((num, idx) => num + idx);
More on .map()
:
But you will lose reference to the same amount of memory instantly. On fairly small array difference would be microsecond at most