Start and end range array count in increments of 1

hi,

So I have 2 numbers 1 and 10, I want to count these in my dropdown in increments of 1
Here is my code so far:

html (angular)

<option *ngFor="let i of yearRange(5, 100)" [value]="i">{{i}}</option>

function is. complaining about .fill()

yearRange(start: number, end: number): number[] {
    return Array(end - start + 1).fill().map((_, idx) => start + idx);
  }

when I remove the .fill() I get a loop but the outputs are blank

I think I managed it here

yearRange(start: number, end: number): number[] {
    return Array(Math.ceil((end - start) / 1)).fill(start).map((x, y) => x + y * 1)
  }

Hi,

You can use Array.from() to generate a sequence of numbers:

Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]

This can easily be adapted to accept a start and end parameters:

function range(start, end) {
  const length = end - start;
  return Array.from({ length }, (_, i) => start + i);
}

range(5, 10);
// [5, 6, 7, 8, 9]

And turned into a handy one liner:

const range = (start, end) => Array.from({ length: end - start }, (_, i) => start + i);

range(95, 100);
// [ 95, 96, 97, 98, 99 ]

In your case that would translate to:

yearRange(start: number, end: number): number[] {
  return Array.from({ length: end - start }, (_, i) => start + i);
}

Which will probably be a bit easier to understand the next time you revisit the code.

3 Likes

Another alternative is to use the keys of a generated array with a spread.
[...Array(end-start).keys()]
< [0,1,2,3]
(I specified end as 5 and start as 1)
But, multiple ways to skin the cat.

1 Like

Good, bad? I don’t know, but playing with generators sometime ago

const rangeIterable = function* (x, y) { while (x < y) yield x++ }

const range = (x, y) => [...rangeIterable(x, y)]

console.log(range(4,10))
// [4,5,6,7,8,9]

could be uglified into one line

const range = (x, y) => [...function* () { while (x < y) yield x++ }()]
2 Likes

Unless I’m missing something, that will always produce a range from 0 to whatever.

const start = 95;
const end = 100;

console.log([...Array(end-start).keys()]);
// [ 0, 1, 2, 3, 4 ]

When what the OP wants is: [ 95, 96, 97, 98, 99 ]

To achieve the desired result, we could just chain a map on the end:

console.log([...Array(end-start).keys()].map(i => i + start));
// [ 95, 96, 97, 98, 99 ]
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.