Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array map with one number in JavaScript [duplicate]

Tags:

javascript

I want to create array with one number. Is it possible?

In array = 60, I mean array[1, 2, 3 ...60], but I want this array with one number.

I want something like this.

JavaScript:

let array = 60;
const map1 = array.map(x => console.log(x));

console.log must happen 60 times.

like image 722
სალი სულაბერიძე Avatar asked Aug 14 '26 06:08

სალი სულაბერიძე


1 Answers

You can use the new Array(60); to make an array of length 60. Then append the fill("") to fill they array with empty strings. After that you can map() the index of each item to its value.

(Be aware that the index is zero based so you need to add one).

let arr = new Array(60).fill("").map((_, i) => i + 1);

arr.forEach(n => console.log(n));

Detailed:

// Create array of length 60
let arr = new Array(60);

// Fill the whole array with a value, i chose empty strings
let filledArr = arr.fill("");

// Replace every value with it's index plus one. Index starts at 0 that's why we add one
let numArr = filledArr.map((_, i) => i + 1);

EDIT: By making it into a function you can call it with dynamic lengths

const makeNumArr = num => new Array(num).fill("").map((_, i) => i + 1);

let fiveArr = makeNumArr(5);
let tenArr = makeNumArr(10);

console.log(fiveArr);
console.log(tenArr);
like image 137
Reyno Avatar answered Aug 16 '26 19:08

Reyno



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!