3

I have an object with strings in it.

filteredStrings = {search:'1234', select:'1245'}

I want to return

'124'

I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.

I've found _.intersection(Array,Array) but this only works with Arrays.

https://lodash.com/docs#intersection

I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.

Thank you for you help.

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
Miguel Coder
  • 1,896
  • 19
  • 36
  • 2
    Now i noticed that mentioned method actually threat/convert strings to (as) arrays, too? https://jsfiddle.net/qm6w2umc/ – sinisake Jan 17 '17 at 22:29
  • Strange, I tried to do it on the website and it didn't work for me. Thanks for your help. If you show this as the answer I will mark it correct, because this is what I ended up using. – Miguel Coder Jan 18 '17 at 01:48

1 Answers1

3

Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).

Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.

var filteredStrings = {search:'1234', select:'124561234'}

var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • That is awesome. I'm going to try that and let you know how it goes. – Miguel Coder Jan 17 '17 at 22:29
  • I want them to be unique. Sorry i didn't mention that. Could you change it back to how you had it before? – Miguel Coder Jan 17 '17 at 23:44
  • This actually worked for me, so I'm going to mark it right, but I ended up using intersection because I decided to parse the arrays before sending them to my component. – Miguel Coder Jan 18 '17 at 01:46
  • 1
    Note that `match()` returns `null` when there are not matches. That means you can't just call `.join()` as shown. You must first verify that you did not get `null`. – Alexis Wilke Nov 28 '18 at 19:20
  • 1
    @AlexisWilke - indeed. Added a fallback. In a case of no matches found, the result would be an empty string. – Ori Drori Nov 28 '18 at 19:25
  • 2
    Note also that this has the potential to silently return incorrect results when `search` contains `]`, ``\``, `^`, `-` in the right places. – Ry- Aug 16 '19 at 22:44