0
\$\begingroup\$

I got a number that can range be either 10, 20, 30, 40... up until 100.

I'd like to make an array from that number. The array should be structured as follows:

If the number is 10, the array should be: [0, 1, 2, 3 ... 10]

If the number is 20, the array should be: [0, 2, 4, 6 ... 20]

If the number is 30, the array should be: [0, 3, 6, 9 ... 30]

Currently, this is my code:

const max = 30

let labels = []
let count = 0

for (let i = 0; i < 10 + 1; i++) {
  labels.push(count)
  count += max/10
}
//[0,3,6,9,12,15,18,21,24,27,30]

This works, but I feel like it can be achieved with fewer lines of code.

I tried something like this:

let f = 0
const arr = Array.from(Array(11), (_, i) => f+=3)
//[3,6,9,12,15,18,21,24,27,30,33]

But as you can see, the output is not correct.

How can I refactor this?

\$\endgroup\$
2
  • 3
    \$\begingroup\$ To anyone in the review queue: only the new suggested code seems to be working incorrectly. The original is claimed to be working. Please leave a comment if you think otherwise. \$\endgroup\$ Commented Sep 14, 2021 at 14:38
  • 2
    \$\begingroup\$ You said "create an array with 10 elements" in title, but your array contains 11 elements. Maybe there are something wrong in your description. \$\endgroup\$ Commented Sep 15, 2021 at 3:28

1 Answer 1

2
\$\begingroup\$

The properly working code had a for loop. To minimize operations visually, we could use Array.from() method (see Array.from() documentation for more). As the question hint states, it is possible to achieve the same result by using Array.from(). The missing part you did was that the first element of the output array should be 0.
The mistake was to add 3 or any other number to the index. In that case, we lose the 0. In order to keep all values, we could use multiplication instead, which will lead the first value to stay ZERO.

The values of the array were filled with this part (x,i)=>max/10*i).
x variable is really unnecessary, it could be whatever.
i is the index of the newly created array which we make by using from().
Each value of the array is made up of the index [0..10] (eleven in total) multiplied by 3 (max/10).

  const max = 30
  labels = Array.from(Array(11).keys(), (x,i)=>max/10*i)

Output:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

\$\endgroup\$
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.