1

I have this var let number = 3

I'd like to create an array with the length based on the number listed above, But the content should be a string like this:

"item {index of item in array}",

so my array should look like this: let array = ['item 0', 'item 1', 'item 2']

Righ now I have this code:

let number = 2
let array = Array.from(Array(number).keys())
// outcome --> [ 0 , 1 ]

But I don't know how to add the strings in a correct way

3 Answers 3

2

Array.from() accepts a callback, and you can use it to create the items.

const number = 2

const array = Array.from(Array(number).keys(), k => `item ${k}`)

console.log(array)

In addition, you can use the index (i) of the item as the counter.

const number = 2

const array = Array.from(Array(number), (_, i) => `item ${i}`)

console.log(array)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this solution

let arr = [...Array(number).keys()].map(x=>`item ${x}`);

or

let arr = [...Array(number)].map((y, x)=>`item ${x}`);

Comments

0

You can try this.

let number = 2;
let array = Array(number).fill().map((ele, i) => `item ${i}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.