15,996,437 members
1.00/5 (1 vote)
See more:
```/*
Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is "num: string". Notice the colon and space in between.

Examples: (Input --> Output)

[] --> []
["a", "b", "c"] --> ["1: a", "2: b", "3: c"]
*/

function orderedArray(array) {
if (array != []) {
let num = 1;
let prefix = `\${num}: `;
for (let i = 0; i < array.length; i++) {
array[i] = prefix + array[i];
num++;
}
return array;
}
return array;
}```

What I have tried:

On codewars, it shows the return result as --> ["1: a", "1: b", "1: c"]. I have tried changing incrementing num before adding the prefix to array[i]. I have tried setting num to other values such as 0, and the result shows --> ["0: a", "0: b", "0: c"], basically whatever the num variable is, it will not increment each element.
Posted
Updated 3-Jun-23 19:55pm

## Solution 2

You want the prefix to be the position in array +1, so.
JavaScript
```/*
Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is "num: string". Notice the colon and space in between.
Examples: (Input --> Output)

[] --> []
["a", "b", "c"] --> ["1: a", "2: b", "3: c"]
*/

function orderedArray(array) {
if (array != []) {
let num = 1;
let prefix = `\${num}: `;
for (let i = 0; i < array.length; i++) {
let prefix = `\${i+1}: `;
array[i] = prefix + array[i];
num++;
}
return array;
}
return array;
}```

Naveen Krishna1 4-Jun-23 13:13pm
Thanks, it worked! it worked even when I kept prefix as \${num}: as long as I put it in the for loop.

## Solution 1

Increment `prefix` inside the loop instead of `num` ... or generate `prefix` inside the loop instead of before it.

v2