Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
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

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;
}
 
Share this answer
 
Comments
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.
Increment prefix inside the loop instead of num ... or generate prefix inside the loop instead of before it.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900