i am trying to solve a code challenge that asks me to fill an array with the value passed as an argument in a function.
For example = fizzBuzz(10)
should return an Array with 10 slots and for each slot increment 1
[0, 1, 2, 3 ,4, 5, 6, 7, 8, 9, 10]
i have tried with a loop and with the fill method but i am having difficulties on this.
This is the first step of the algorithm. Can someone help me ?
Here is my last attempt:
function fizzbuzz(n) {
// Write your code here
const array = new Array(n)
for(let i = 0; i < n; i ) {
array.fill(n, 0))
}
return array
}
This wont work cause the fill method is only called once for every slot i guess. Can someone help me ?
I have tried with the forEach method, fill method and with a loop, but i am unable to solve the first step of this algorithm.
I need nelp solving the first step of this algorithm.
CodePudding user response:
So: you are learning to use arrays.
Let's start with the basics.
An array is a kind of variable that points to a list of things.
Javascript simulates traditional arrays by numbering each element:
const array = new Array(10);
But javascript is not vary rigid about how many elements are in an array, so you could also say:
const array = [];
There's a difference between these two, even though absolutely nothing is in it yet: the first form has 10 undefined values. The second form as no values and a length of 0. But they both work just fine.
How do you access elements in this list? By number!
console.log(array[0]);
In both of the above cases, you are going to get "undefined" as a result.
Now to understand your homework, all you need to know is how to assign values to the array. The array object method "fill" is no good, because what your initial loop does is assign ALL elements to 0, and then to 1, and then to 2, etc. That's no good. Who knows why we even have a "fill" method. I've never used it in my life.
But what happens ALL THE TIME is:
const array = [];
for (let i=0; i < n; i ) {
array[i] = i;
}
What is happening here?
The element in the list at position 0 is set to 0. The element in the list at position 1 is set to 1. And so on.
Because it is javascript, there are actually MANY ways to do this. This is just one. Using "fill" is not one. But this is the most fundamental pattern common across most languages, so it is a good one to master before moving on to fancier approaches.
CodePudding user response:
If you are trying to created an Array of size
N
with values from0...N
then the size of the array should be N 1.For initializing the array
- You can use ES6 using Array
keys()
andspread operator
.
const N = 10; const array = [...Array(N 1).keys()] // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- If you want to use for loop, then you can populate the array like this:
const N = 10; const array = new Array(N 1); for(let i=0; i<array.length; i ) { array[i] = i; } // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- You can use ES6 using Array