1

I want to get array with the range [1,1.1,1.2 ...... 9.9,10]

I wrote this code which returns me from 1.1 until 9.9

  1. Is there a shorter way to get this range in JavaScript? Seems like lots of code.
  2. How can I get the number 1 and 10 as well?
let ratingRange = Array(10).fill().map((v,i)=> {
    return Array(10).fill().map((v,decimalI)=> {
        let value = parseFloat(`${i}.${decimalI}`)
       return value > 1 ? value : false 
    })
}).flat().filter( v => v > 0.9  );
// [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9]
BenB
  • 2,747
  • 3
  • 29
  • 54
  • 1
    `0.1` is well-behaved in base 10 but not in base 2. – Paul Nov 11 '20 at 06:19
  • 1
    `Array.from({length: 89}, (_, i) => (i+11) / 10);` it can be generalised to any range `[from, to]` with increments of 0.1 using `const range = (from, to) => Array.from({length: ((to - from) * 10 - 1)}, (_, i) => (i + ((from) * 10 + 1)) / 10);` – VLAZ Nov 11 '20 at 06:27
  • @VLAZ this does not return 1 and 10 – BenB Nov 11 '20 at 06:30
  • @BenB your example output doesn't have them, either. Should the bounds be inclusive or exclusive? – VLAZ Nov 11 '20 at 06:31
  • @BenB Since it's not really clear wither you want inclusive or exclusive bounds and which ones, just [take your pick from here](https://jsbin.com/rapisitosi/1/edit) – VLAZ Nov 11 '20 at 06:45

4 Answers4

2

You can do this.

Try!

const arr = [];

for(let i=10; i<=100; i++) {
  arr.push(i);
}

const range = arr.map(n => n/10);
console.log(range);
hyundeock
  • 445
  • 1
  • 6
  • 15
0

This is what you need:

let arr = [];

for (let i = 1.1; i < 10; i += 0.1)
  arr.push(i);

console.log(arr)
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Nov 11 '20 at 06:22
0

Here you go.

let val = 1.0, nums = [];
while (val < 9.9) {
  val = Math.round((val + 0.1) * 10) / 10
  nums.push(val);
}
console.log(nums);
Gerard
  • 15,418
  • 5
  • 30
  • 52
0

You can use Array.from.

Difference with new Array and Array.from is that new Array returns a jagged array. So you cannot loop on it. Using fill works but then it fills single value. Array.from fills the gap and accept a mapper function as second argument

const result = Array.from(
  { length: 9 },
  (_, i) => Array.from(
    {length: 10},
    (__, index) => (i + 1) + index * 0.1
  )
).flat()

console.log(result)
Rajesh
  • 24,354
  • 5
  • 48
  • 79