Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Object Array with a Given Range

Looking for some possible solutions without using a for loop.

I have an object that looks like this:

Object:

[{id:1, score:1000, type:"hard"}, {id:2, score:3, type:"medium"}, {id:3, score:14, type:"extra hard"}, {id:5, score:-2, type:"easy"}]

Range:

var range={min:0, max:15}

Is there an elegant way of fetching all objects with a score between the range given?

The given range would return:

[{id:2, score:3, type:"medium"}, {id:3, score:14, type:"extra hard"}]

I was checking lodash 3.0 but there doesn't seem to be a built in range filter for this.

like image 794
lost9123193 Avatar asked Jan 04 '23 18:01

lost9123193


2 Answers

Use Array#filter method.

var res = arr.filter(function(o) {
  // check value is within the range
  // remove `=` if you don't want to include the range boundary
  return o.score <= range.max && o.score >= range.min;
});

var arr = [{
  id: 1,
  score: 1000,
  type: "hard"
}, {
  id: 2,
  score: 3,
  type: "medium"
}, {
  id: 3,
  score: 14,
  type: "extra hard"
}, {
  id: 5,
  score: -2,
  type: "easy"
}];

var range = {
  min: 0,
  max: 15
};

var res = arr.filter(function(o) {
  return o.score <= range.max && o.score >= range.min;
});

console.log(res);
like image 99
Pranav C Balan Avatar answered Jan 07 '23 07:01

Pranav C Balan


Quite trivial with filter, but since you asked for "elegant", how about:

// "library"

let its = prop => x => x[prop];
let inRange = rng => x => rng.min < x && x < rng.max;
Function.prototype.is = function(p) { return x => p(this(x)) }

// ....

var data = [{id:1, score:1000, type:"hard"}, {id:2, score:3, type:"medium"}, {id:3, score:14, type:"extra hard"}, {id:5, score:-2, type:"easy"}]

var range={min:0, max:15}

// beauty

result = data.filter(
  its('score').is(inRange(range))
);

console.log(result)

Easy to extend for things like its('score').is(inRange).and(its('type').is(equalTo('medium')))

like image 36
georg Avatar answered Jan 07 '23 08:01

georg