0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

7

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);
Reyno
  • 6,119
  • 18
  • 27
  • what ```_``` is for ? – xMayank Jun 24 '20 at 08:28
  • thanks for your unswer, but why this array start with 11? – სალი სულაბერიძე Jun 24 '20 at 08:28
  • @MayankGupta `_` is just a variable name for the current item in de array. I could have chosen a different name but `_` is common name for variables you don't use. [Array.map](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/map) has more info about the method – Reyno Jun 24 '20 at 08:30
  • 2
    @სალისულაბერიძე It's because on stackoverflow we can only show 50 lines in the console. If you copy it to your own code it should show all 60. – Reyno Jun 24 '20 at 08:31
-1

I think you're looking for this. You can use map when you want to return a new array. If you just want to iterate your should use forEach.

let array = new Array(60).fill(1);
array.forEach(x => console.log(x));
ABGR
  • 4,631
  • 4
  • 27
  • 49