-3

for example :

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

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

2
  • what is the expected outcome? Commented Oct 16, 2019 at 5:45
  • Where is your try? Commented Oct 16, 2019 at 5:47

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.