los*_*193 3 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"}]
Run Code Online (Sandbox Code Playgroud)
范围:
var range={min:0, max:15}
Run Code Online (Sandbox Code Playgroud)
是否有一种优雅的方式来获取所有具有给定范围之间分数的对象?
给定的范围将返回:
[{id:2, score:3, type:"medium"}, {id:3, score:14, type:"extra hard"}]
Run Code Online (Sandbox Code Playgroud)
我正在检查 lodash 3.0,但似乎没有为此内置范围过滤器。
使用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;
});
Run Code Online (Sandbox Code Playgroud)
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;
});
Run Code Online (Sandbox Code Playgroud)
相当简单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)Run Code Online (Sandbox Code Playgroud)
易于扩展,例如 its('score').is(inRange).and(its('type').is(equalTo('medium')))
| 归档时间: |
|
| 查看次数: |
2797 次 |
| 最近记录: |