使用给定范围过滤对象数组

5

寻找不使用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,但似乎没有内置的range过滤器。

2个回答

6

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


5

使用 filter 很简单,但既然您要求“优雅”,那就这样:

// "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)

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

可以实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接