Skip to content
Advertisement

Javascript: array difference but occurrencies between parentheses

Say we have 2 arrays

JavaScript

The difference between these 2 arrays

JavaScript

so diff is equal to ['2', '4']

My problem is that I could have

JavaScript

and I want to get this array

JavaScript

Advertisement

Answer

Your data format is awkward. If you can take decisions on that, I advise you to do instead (for an array like ['1', '2', '3(4)', '4', '5']):

  • use a flat array with as many occurrences as it gets for each element, like:

    JavaScript
  • use an array of tuples, whose second value in each element is its count, like:

    JavaScript
  • use a map-like object, whose value is the count, like:

    JavaScript
  • use an array of only the counts, where the index is implicitly the key:

    JavaScript

Any of those would make your like easier.


If none of that is a valid option for you, I will point you in the right direction of implementing a function to compare 2 elements are yield the merged difference value according to the rules you have:

JavaScript

You can start from here to iterate through your arrays and generate the differences with the merged values.

Advertisement