Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash / js: Filtering values within an object based on regular expressions and getting the highest by comparison

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?

like image 881
overflower Avatar asked Apr 19 '17 05:04

overflower


People also ask

Why you should not use Lodash?

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.

How does Lodash filter work?

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.

What is _ get?

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


1 Answers

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);
like image 72
guest271314 Avatar answered Nov 12 '22 13:11

guest271314