Array Manipulation

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']

So you mean you want to replace the existing array or create a new array that looks like below?

['milk (0)', 'bread (1)', 'eggs (2)']

Either way, you should give it a try first and show us what you have tried.

I want to replace the existing array.

Have you thought about an algorithm yet? Try and write out the steps you would take to do it by hand.

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

1 Like

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():

1 Like

True, but why create the need for additional memory (using map) if it is not needed?

But you will lose reference to the same amount of memory instantly. On fairly small array difference would be microsecond at most :slight_smile:

1 Like