Array issue in inserting n natural numbers

i am trying to make a function that takes n as a parameter and gives the first n natural numbers as a list in an array.

e.g myarray(6)

--------------output------------------

myarray = [1,2,3,4,5,6]

So what do you have so far?

i am barely moving. was able to insert one element at a time. thats it. some of my practice programs are stuck at it.

function array(a){

const arr = ;

for ( i = 1;i<a;i++){

let x = [i]

console.log(x)

}}

array(5)
---------output--------
test.js:6 [1]
test.js:6 [2]
test.js:6 [3]
test.js:6 [4]

We would need to see your code before we could help you. You can paste it in here (wrap it with triple backticks).

Unless I am not understanding the requirements correctly, this seems like a rather straight forward problem. You just need to fill an array with the numbers 1,…,n. Do you know how to add an element to an array? Do you know how to create a loop that will do that n times?

Is the function supposed to return an array?

–Do you know how to add an element to an array?
yes, i am using the push method.
–Do you know how to create a loop that will do that n times?
yes, however i am unable to integrate it with push.
here is a snap of my code, right side is the output


i know const arr is not required in the code
i am a beginner, so still learning

Please don’t post images of code. You can directly put your code in this forum, you just have to put triple backticks before the beginning of the code block and immediately after the end of the code block.

I am seeing that you are using a for loop to count from 1 to a-1 (I think you will want to fix that so that it includes a). And it sounds like you are familiar with the Array.push() method. So don’t you need to push each of the numbers you iterate through in the for loop into the array you created at the beginning?

And yes, you should have const array = [] at the beginning. You are doing that correctly.

sure. let me give it a try. thanks.

this worked :joy: and i am so happy that i named it “happyarray(n)”
here is the code

function happyarray(n){

var arr = [];

for(i=1; i<=n;i++) {

arr.push(i);
}
console.log(arr)
} 

thank you so much for the help.

you have one last issue, your function returns undefined. You want it to return your output.

let me check…

function happyarray(a){

var arr = [];

for(i=1; i<=a;i++) {

arr.push(i);

}

console.log(arr)

}

happyarray(20) /// calling the function here 
/// output is : (20) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

it seems to be working superfine this side. I am not sure why it is showing undefined there.

no, try with console.log("output from the function is: " + happyarray(6))

you are not printing the output of the function

got it now. I used return at the end and now it is showing the required output.