-3

for example :

var array2 = [{"A":1},{"B":2},{"C":3},{"D":4},...];

How to get specified range data(like 11~20 data)?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Benji
  • 37
  • 6

2 Answers2

1

Seems you are looking for this:

var array2 = [{"A":1},{"B":2},{"C":3},{"D":4},{"E":5},{"F":6},{"G":7},{"H":8},{"I":9},{"J":10},{"K":11},{"L":12},{"M":13},{"N":14},{"O":15},{"P":16},{"Q":17},{"R":18},{"S":19},{"T":20},{"U": 21}];

var rangeMin = 11;
var rangeMax = 20;
var result = array2.filter((item) => item[Object.keys(item)[0]] >= rangeMin && item[Object.keys(item)[0]] <= rangeMax);

console.log(result);
Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20
0

If your array is always in ascending order, increasing by one each object, you could use .slice(), which will give you a portion of your array from a starting index to an ending index:

const arr = [{"A":1},{"B":2},{"C":3},{"D":4},{"E":5}];

const getValuesInRange = (arr, x, y) => 
  arr.slice(x-1, y);

console.log(getValuesInRange(arr, 2, 4));

Alternatively, could use Object.values() to get the numeric value from each object and use that with .filter to only keep those objects where the numeric value is in between your given range:

const arr = [{"A":1},{"B":2},{"C":3},{"D":4},{"E":5}];

const getValuesInRange = (arr, x, y) => 
  arr.filter(obj => {
    const n =  Object.values(obj).pop();
    return x <= n && n <= y;
  });

console.log(getValuesInRange(arr, 2, 4));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64