对于下面的json
[
{
"index": "xyz",
...
},
{
"index": "abc1234",
...
},
{
"index": "xyz",
...
},
{
"index": "abc5678",
...
}
...
我想分别过滤掉 abc 值和 xyz 值。
我尝试了以下方法来获取值
var x = _.filter(jsonData, function (o) {
return /abc/i.test(o.index);
});
它可以提供过滤后的输出。
现在我想获得最高的 abc 值,如果有值 abc123, abc444, abc999 那么代码应该返回 abc999。
我可以使用 lodash 再次循环,但这是否可以在一次调用中完成 - 在同一个过滤掉的调用中?
最佳答案
你可以使用 Array.prototype.reduce(), String.prototype.replace() 和 RegExp /\D+/ 匹配和删除不是数字的字符。检查字符串的前一个数字部分是否小于字符串的当前数字部分
var jsonData = [
{
"index": "xyz",
},
{
"index": "abc1234",
},
{
"index": "xyz",
},
{
"index": "abc5678",
},
{
"index": "abc1",
}];
var x = jsonData.reduce(function (o, prop) {
return /abc/i.test(prop.index)
? !o || +prop.index.replace(/\D+/, "") > +o.replace(/\D+/, "")
? prop.index
: o
: o
}, 0);
console.log(x);
关于javascript - lodash/js : Filtering values within an object based on regular expressions and getting the highest by comparison,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43487553/