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
    A simple for loop would suffice – j08691 Nov 22 '21 at 14:53
  • do you have some example? –  Nov 22 '21 at 14:53
  • 5
    of a `for` loop? – pilchard Nov 22 '21 at 14:54
  • `Array(121-17).fill().map((x, i) => { return { value: i+17, label: i+17 }})` – angel.bonev Nov 22 '21 at 14:56
  • Dupe of: [Create array of all integers between two numbers, inclusive, in Javascript/jQuery](https://stackoverflow.com/questions/8069315/create-array-of-all-integers-between-two-numbers-inclusive-in-javascript-jquer) or [Efficient way to create and fill an array with consecutive numbers in range](https://stackoverflow.com/questions/55579499/efficient-way-to-create-and-fill-an-array-with-consecutive-numbers-in-range), ... – Andreas Nov 22 '21 at 15:01

3 Answers3

6

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)
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • 1
    might as well show the math for clarity `Array.from({length: 120-17+1}, (_, i) => i + 17)` (and avoid the error you just fixed :)) – pilchard Nov 22 '21 at 14:56
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

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.

j08691
  • 204,283
  • 31
  • 260
  • 272