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.
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);
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')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With