Reputation: 23
I am looking to create a javascript function that outputs strings as a result of array multiplication.
The first number of the array will be multiplied by the second, resulting in a string as below.
For ex. when:
console.log(repeatNumbers([[1, 10]]));
console.log(repeatNumbers([[1, 2], [2, 3]]));
The result would be:
1111111111
11, 222
I am struggling getting past returning simple multiplication out puts such as 1*10 = 10, and producing a full string (w/o commas) instead.
Any advice would be great - thanks.
Upvotes: 0
Views: 44
Reputation: 3731
actually you can do it using a map
over the array
and then apply the repeat
function of string
(you have to parse from number
to string
).
repeatNumbers = (array) => array.map(item => item[0].toString().repeat(item[1]));
console.log(repeatNumbers([
[1, 10]
]));
console.log(repeatNumbers([
[1, 2],
[2, 3]
]));
Upvotes: 3
Reputation: 32176
You can use the array constructor function to create an array of a given length. Then use the .fill
array method to fill the new array with the right thing. Finally, you can use join
to convert the filled array back to a string. In your case, for each pair, the first element is what to fill the array with, and the second is the desired length.
Perform that process for each item in the passed array (using map
), and join them with commas, and you get the result from your example:
function repeatNumbers(arr) {
return arr
.map(pair => Array(pair[1]).fill(String(pair[0])).join(""))
.join(", ");
}
console.log(repeatNumbers([[1, 10]]));
console.log(repeatNumbers([[1, 2], [2, 3]]));
Upvotes: 1