For the following json
[
{
"index": "xyz",
...
},
{
"index": "abc1234",
...
},
{
"index": "xyz",
...
},
{
"index": "abc5678",
...
}
...
I want to filter out abc values and xyz
values separately.
I tried the following to get values
var x = _.filter(jsonData, function (o) {
return /abc/i.test(o.index);
});
and it worked to give the filtered outputs.
Now i want to get the highest of abc
values that is if there values abc123
, abc444
, abc999
then the code should return abc999
.
I can loop over again using lodash but could this be done in a single call - within the same one that filters out?
Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.
The filter() function has a couple convenient shorthands for dealing with arrays of objects. If you pass a string predicate instead of a function, Lodash will filter by whether that property is truthy or falsy. If your predicate is an object obj , Lodash will filter objects that match the given predicate.
The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])
You can use Array.prototype.reduce()
, String.prototype.replace()
with RegExp
/\D+/
to match and remove characters that are not digits. Check if previous number portion of string is less than current number portion of string
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With