0

what is the fastest way to create array from number 17 to number 120?

[17,18,20,...,118,119,120]

I tried to use Array method but its start with 0 and slice from some resson cut the last numbers and not the firsts numbers.

export const ARR_OF_AGES = Array(121).fill().slice(16).map((x, i) => {
  return { value: i, label: i }
})
5

3 Answers 3

7

The following should work.

Array.from({length: 120 - 17 + 1}, (_, i) => i + 17)

See working example below:

const result = Array.from({length: 104}, (_, i) => i + 17)
console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

might as well show the math for clarity Array.from({length: 120-17+1}, (_, i) => i + 17) (and avoid the error you just fixed :))
0

If your array starts with 17 and ends with 120 it means it has 104 elements. So change 121 to 104 in your code, and instead of giving value "i" to your elements, give them value "i+17". That way your i-th element will have value i+17 meaning your array will start from 17

4 Comments

Don't forget to remove the .slice(16) then.
It would be nice if some code would follow the explanation :)
oh, yeah, i didn't see the slice. Tnx!
Array((120-17+1)/*104*/).fill().map((x, i) => { return { value: i + 17, label: i + 17 } })
0

Since you asked for "fastest", and I suggested using a for loop in the comments above, I thought that'd I'd at least give you a simple example:

let ary = [];
for (let i = 17; i <= 120; i++) {
  ary.push(i);
}

Running some simple performance tests shows that this method is over an order of magnitude faster then the result you accepted. So yeah, fast. And easy to understand.

Comments