Using Array.map With Repeat In Javascript
Solution 1:
You could convert the number to string, repeat the value and convert it back to number.
var a = [1, 2, 3]
a = a.map(a => +a.toString().repeat(2));
console.log(a);
Solution 2:
Given that you seem to be looking for repeating the digits, use strings for that. Which have a handy repeat
method for this purpose:
a.map(x =>Number(String(x).repeat(2))));
If you want to use your notation, you need to make a higher-order repeat
function that returns another function to be used as the map
callback:
functionrepeat(times) {
returnx =>String(x).repeat(times);
}
a.map(repeat(2)).map(Number)
Solution 3:
Yes that is possible. You can define repeat
as a function that returns a function:
functionrepeat(times) {
returnfunction (value) {
return +String(value).repeat(times);
}
}
// Your code:var a = [1, 2, 3];
var result = a.map(repeat(2));
console.log(result);
The map
method expects a function as argument, so the call to repeat(2)
should return a function. That (inner) function uses String#repeat
after converting the value to string, and then converts the result back to number with the unary +
.
Solution 4:
Here you go, number
version and string
version
constdoubleIt = n => Number(`${n}${n}`);
const arr = [1, 2, 3, 55];
const strArr = arr.map(o =>`${o}${o}`);
const numArr = arr.map(o => o * 11);
const numFromStringsArr = arr.map(o =>doubleIt(o));
console.log(strArr);
console.log(numArr);
console.log(numFromStringsArr);
Solution 5:
You can create an array of N .length
with Array()
, use Array.prototype.fill()
to fill the created array with current element of .map()
callback, chain Array.prototype.join()
with ""
as parameter, use +
operator to convert string to number
var a = [1, 2, 3], n = 2;
a = a.map(el => +Array(n).fill(el).join(""));
console.log(a);
Post a Comment for "Using Array.map With Repeat In Javascript"