0

I got an issue trying to reduce with _.filter method a list of (valid) ids. The aim is to create a new id according to the last value of the number given at the end of each string (string-string-[lastNumber+1]).

Because I do not want to receive an invalid id. I just tried to filter these ids using the regexp inside of _.filter method.

However, the result looks very weir. Despite the fact that of these strings passed the online test of regexp validation.

REPL testing

var data = [ 
  'offstreetparking-estepona-1',
  'offstreetparking-estepona-2',
  'offstreetparking-estepona-3',
  'offstreetparking-estepona-04', // Should nor be included (not 04)
  'offstreetparking-estepona-4',
  'offstreetparking-estepona-5'
]

var patt = /([A-Za-z]+)-([A-Za-z]+)-([1-9]+)/g;

_.filter(data, d => patt.test(d));


// Result from lodash => [
"offstreetparking-estepona-1", 
"offstreetparking-estepona-3", 
"offstreetparking-estepona-4"
]

// Missing => 2 and 5 ids!

I don't know why some of valid ids are not passing the test inside of _.filter function and are returned as element of the array.

All of them were tested independently and works fine :(

The wrong behavior that lodash returned just the odds values...

Any other solutions are welcome, but I want to know why lodash is not working properly at this point.

Many thanks!

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Ivan Sanchez
  • 546
  • 5
  • 17
  • Heh, my parents used to live in Estepona. :-) – T.J. Crowder Mar 29 '19 at 10:05
  • The problem is the global flag. There's a dupetarget for this, I'll find it. The problem is that the regular expression tries to pick up from just after the last match. Remove the `g` (and probably add anchors, `^` at the beginning and `$` at the end) and it'll work: https://jsfiddle.net/tjcrowder/purksy40/ – T.J. Crowder Mar 29 '19 at 10:06
  • Possible duplicate of [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) – T.J. Crowder Mar 29 '19 at 10:06
  • Hey mate! Love to hear that your parents enjoyed the south of Spain :) – Ivan Sanchez Mar 29 '19 at 10:19
  • I already solved this stupid issue: `/^([A-Za-z]+)-([A-Za-z]+)-([1-9]+)([0-9]*)$/` – Ivan Sanchez Mar 29 '19 at 10:20
  • :-) This was ~1963, before it was the resort town it is now. – T.J. Crowder Mar 29 '19 at 10:20
  • Your best bet here is just to delete the question, since it's a duplicate of an existing one and probably doesn't add to the searchability. – T.J. Crowder Mar 29 '19 at 10:21

0 Answers0