0

I have been learning about ranges and also Object.keys and map, but I am wondering if this is possible:

{
  "zero": 0,
  "ten": 10,
  "twenty": 20,
  "thirty": 30
}

Given a number between 0 and 30, is there a way to determine what two numbers it is between?

For example,

Object.keys(range).map((v) => {
  if (15 > range[v] && 6 < range[v+1]) {
    // print out lower and upper 
  }
});
user1354934
  • 6,033
  • 10
  • 40
  • 61
  • `map` returns one thing for every one thing in a collection. If you are just going to print (or something similar), `forEach` is probably a better choice. – Davin Tryon Apr 11 '17 at 20:42
  • Why would you make `range` an non-array object? The property names don't add anything useful, and it is bad practice to assume any order in which `Object.keys` iterates over the object properties. Also: you speak of one number, but then have code with two different numbers (6 and 15)... – trincot Apr 11 '17 at 20:44
  • please add some use cases and the wanted results. – Nina Scholz Apr 11 '17 at 21:15

2 Answers2

2

It is not such a good idea to use a non-Array object for range:

  • The property names do not add much to the meaning of the object
  • The order in which property names are iterated is a complex issue, and better not relied upon.

Better would be to use an array, and then use the find or findIndex method:

function getInterval(range, n) {
    var i = range.findIndex( i => n < i );
    if (i < 0) i = range.length;
    // return an array with the two values that "bound" the value: 
    return [range[i-1], range[i]];
}

var range = [0, 10, 20, 30];
// Examples: note that one value can be undefined, when outside of the range
console.log('-2: ' + JSON.stringify(getInterval(range, -2)));
console.log('6: ' + JSON.stringify(getInterval(range, 6)));
console.log('15: ' + JSON.stringify(getInterval(range, 15)));
console.log('31: ' + JSON.stringify(getInterval(range, 31)));
Community
  • 1
  • 1
trincot
  • 211,288
  • 25
  • 175
  • 211
1

You could check the interval and print the key.

var range = { zero: 0, ten: 10, twenty: 20, thirty: 30 },
    interval = [15, 25];

Object.keys(range).forEach(v => interval[0] < range[v] && range[v] < interval[1] && console.log(v));

A different approach with a single value for an interval of the object properties

var range = { zero: 0, ten: 10, twenty: 20, thirty: 30 },
    value = 15;

Object.
    keys(range).
    sort((a, b) => range[a] - range[b]).
    forEach((k, i, kk) => (range[kk[i - 1]] <= value && value <= range[k] || range[k] <= value && value <= range[kk[ i + 1]]) && console.log(k));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324