I am trying to merge two sets of analytical data from two different providers. The arrays, country name along with a metric, are arranged as follows:
[['Albania','1000'],['Australia','1000']]
Both data sets can contain different versions of the same country name (such as UK instead of United Kingdom). How can I go about merging these arrays of arrays in Javascript? By merge I mean combine the data sets for each country into a single set of arrays.
Example:
[['Albania','1000'],['United Kingdom','1000']]
+
[['Albania','1000'],['UK','1000']]
=
[['Albania','2000'],['United Kingdom','2000']]
Clarifications: Our mobile sites use one analytics provider where as our main global sites use another, different analytics provider. We need to merge these data sets to create an accurate report. There will only ever be 2 data sets needing to be merged.
Here is a partial solution translated from the PHP post. This does not get you aliasing. The equivalent code in PHP looks a lot cleaner because of associative arrays. You could obtain a very nice solution if you had object literals instead of arrays to work with. This solution may require shims for
Array.indexOfand possiblyArray.concatdepending on your platform.http://jsfiddle.net/radu/8JQBS/
This produces:
[['Albania', '2000'], ['United Kingdom', '1000'], ['UK', '1000']]. You could implement aliasing for this, but it’s annoying – see below for a better solution.Here is another solution which instead of producing an array of arrays as a result, gives an object literal. In my opinion this is much better. You may not be able to control the data you get from whatever API you’re using, but you can control how you process it, and this should make downstream code better. This may require a shim for
Object.hasOwnProperty.http://jsfiddle.net/radu/fPsdc/
This produces:
{'Albania' : 2000, 'United Kingdom' : 2000}. If you really must have an array of arrays as a result.. you can do this: