过滤具有给定范围的对象数组

时间:2017-01-10 07:24:54

标签: javascript arrays filtering

在不使用for循环的情况下寻找一些可能的解决方案。

我有一个看起来像这样的对象:

对象:

[{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}

是否有一种优雅的方式来获取所有对象的得分范围?

给定范围将返回:

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

我正在检查lodash 3.0,但似乎没有内置范围过滤器。

2 个答案:

答案 0 :(得分:3)

使用Array#filter方法。

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

答案 1 :(得分:3)

filter非常简单,但是因为你要求&#34;优雅&#34;,怎么样:

&#13;
&#13;
// "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)
&#13;
&#13;
&#13;

易于扩展its('score').is(inRange).and(its('type').is(equalTo('medium')))

等内容