Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript generate array of strings with inline solution

There simple code:

var arr = [];
for(var i = 0; i < 10; i++){
    arr.push("some string with iterating value "+i);
}

I wonder if there is a one-line solution in which I enter the string and the maximum value and get an array of generated lines.

like image 484
el pax Avatar asked Jun 07 '26 16:06

el pax


2 Answers

Try this, if the input is 5, you can have it as N and get the input from user

DEMO

var result = Array.from(new Array(5),(val,index)=> "some string " + index );
console.log(result);
like image 148
Sajeetharan Avatar answered Jun 10 '26 05:06

Sajeetharan


const newArray = [...Array(10)].map((_, i) => `some string with iterating value ${i}`)
console.log(newArray)

You can use a spread operator and create a new array of the length you require, loop (map) over it and return the string. This will create a new array of the length (10) with the string you want in it.

like image 44
putvande Avatar answered Jun 10 '26 05:06

putvande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!