javascript - Intersection of characters in two strings - Stack Overflow

I have an object with strings in it.filteredStrings = {search:'1234', select:'1245'

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.

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.

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./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.

Share Improve this question edited Mar 22, 2019 at 11:16 laggingreflex 34.7k36 gold badges144 silver badges200 bronze badges asked Jan 17, 2017 at 22:19 Miguel CoderMiguel Coder 1,94720 silver badges36 bronze badges 2
  • 2 Now i noticed that mentioned method actually threat/convert strings to (as) arrays, too? jsfiddle/qm6w2umc – sinisake Commented Jan 17, 2017 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 Commented Jan 18, 2017 at 1:48
Add a ment  | 

1 Answer 1

Reset to default 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246766a4618444.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信