Repeat the Same Item Multiple Times

Tell us what’s happening:
My question is - Is there a simple way to achieve this using ES6 or any older methods?

I have provided my solution at the bottom.

Note: Someone posted that this can be solved using Array.prototype.from method.

Problem:
Create a function that takes two arguments (item, times). The first argument (item) is the item that needs repeating while the second argument (times) is the number of times the item is to be repeated. Return the result in an array.

Examples

"edabit", 3 ➞ ["edabit", "edabit", "edabit"]

13, 5 ➞ [13, 13, 13, 13, 13]

"7", 2 ➞ ["7", "7"]

0, 0 ➞ []

Notes
item can be either a string or a number.
times will always be a number.

Your code so far

function repeat(item, times) {
	let rslt = [];
	for(let i = 0; i < times; i++) {
  	rslt.push(item)
  }
  return rslt;
}

The above code will repeat the item that you pass in whether it’s a string or a number.

That sounded interesting so I looked into it some. Maybe this will help

There were also some cool tricks here too especially the Bonus Answer

Try this

function repeat(item,times){
    return new Array(times).fill(item);
}
3 Likes