5

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.

2 Answers 2

6

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

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

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.