beek
beek

Reputation: 3750

Javascript build a string from the length of an array of ?,

Is there a pretty way of building a string of something like (?,?,?) for the number of items in an array

I've tried

values.map(() => '?,')
values.reduce((a,b) => {a + '?,'},'')

but both are not working

Upvotes: 1

Views: 51

Answers (4)

Bargros
Bargros

Reputation: 531

You could simply use the arrays forEach() extension, like this:

var string = "";
[1,2,3,4,5,6,7,8,9].forEach((elem, index) => string += "?");

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could map question marks for each element and join the array in an template literal.

var array = [1, 2, 3],
    string = `(${array.map(_ => '?').join()})`;
    
console.log(string);

Upvotes: 2

Amit Chauhan
Amit Chauhan

Reputation: 6869

You need to return from map and reduce functions.

var valuse = [1,2,3]
var newValues = values.reduce((a,b) => a === '' ? '?' : a + ',?','');
console.log(newValues);

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

  "(" + values.map(el => "?").join() + ")"

You could just join them.

Upvotes: 1

Related Questions