0

Suppose I have 2 string arrays from different sources and I want to check if both of them have any values in common, what would be the best approach in Typescript. What would be even better is, if we could find a degree of likeness between them.

Of-course looping through each elements and comparing them individually would work, but I'm looking for a more efficient approach.

  • Consider values in array to be unique
  • Let's assume they're strings for this example. But even if they're custom objects, they would have an inherent "compare" method to check equality.
  • Degree of likeness : If all values match then 100% ; if half of the values match 50% . For eg: ["a","b"] and ["a"] would return 50 %. For 100% match, the number of items in both arrays will also have to be same.

And thanks in advance!!

  • Are elements in the arrays unique? How do you define the "degree of likeness"? Are elements always simple primitive values? – Robby Cornelissen Mar 15 '23 at 07:03
  • Yes. Consider the values unique. If all values match then 100% ; if half of the values match 50% etc.. – Sreehari S Mar 15 '23 at 07:05
  • 1
    So, what would be the degree of likeness for `["a","b"]` and `["a"]`? 100% or 50% – derpirscher Mar 15 '23 at 07:10
  • 50% I would say, since only half the values match. Let me also edit the question to make these conditions clear. Thanks!! – Sreehari S Mar 15 '23 at 07:13
  • See for instance https://stackoverflow.com/questions/75581868/intersection-of-2-arrays-containing-objects on how to create the intersection of two arrays. Then you can calculate your likeness based on the size of the original array and the size of the intersection – derpirscher Mar 15 '23 at 07:15
  • If likeness for `['a', 'b']` and `['a']` is 50%, then what is it for `['a', 'b']` and `['a', 'b', 'c']`? 100% or 66.66...%?Is the degree of likeness between `['a', 'b']` and `['a']` the same as the degree of likeness between `['a']` and `['a', 'b']`? Question lacks clarity. – Robby Cornelissen Mar 15 '23 at 07:16
  • @RobbyCornelissen Have edited my question to include more details as per your suggestion. Apologies for any inconvenience. P.S : I'm new to StackOverflow – Sreehari S Mar 15 '23 at 07:20
  • Please provide enough code so others can better understand or reproduce the problem. – Community Mar 15 '23 at 09:09

0 Answers0