JQuery and JavaScript have ready made functions like merge(), JavaScript concat(), extend() that can make your work easy to merge two arrays. But in this article we are going to discuss different scenario. Merge two arrays with key and value pairs. When we are merging two arrays with key and value pairs, we have to take care about two things. (1) if key matched, then value should be updated and (2) if key not found it would be added to base array.
We used .reduce function that makes operation fast to find matching keys.
Code of Conduct
- var array1 = [
- ["01/05/2015", 2],
- ["01/06/2015", 1],
- ["01/07/2015", 11],
- ["01/08/2015", 8],
- ["01/10/2015", 3]
- ];
- var array2 = [
- ["01/01/2015", 10],
- ["01/02/2015", 9],
- ["01/03/2015", 15],
- ["01/04/2015", 1],
- ["01/05/2015", 3],
- ["01/06/2015", 3]
- ];
- var result = array1.concat(array2)
- .reduce(function (ob, ar)
- {
- if (!(ar[0] in ob.nums))
- {
- ob.nums[ar[0]] = ar
- ob.result.push(ar)
- }
- else
- {
- ob.nums[ar[0]][1] += ar[1]
- }
- return ob
- },
- {
- nums:
- {},
- result: []
- })
- .result.sort(function (a, b)
- {
- return new Date(a[0]) - new Date(b[0]);
- });
- $('body')
- .append(JSON.stringify(result));
Example
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Array Concat Example</title>
- <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
- <script>
- $(function() {
- var array1 = [["01/05/2015", 2], ["01/06/2015", 1], ["01/07/2015", 11], ["01/08/2015", 8], ["01/10/2015", 3]];
- var array2 = [["01/01/2015", 10], ["01/02/2015", 9], ["01/03/2015", 15], ["01/04/2015", 1], ["01/05/2015", 3], ["01/06/2015", 3]];
- var result =
- array1.concat(array2)
- .reduce(function (ob, ar) {
- if (!(ar[0] in ob.nums)) {
- ob.nums[ar[0]] = ar
- ob.result.push(ar)
- } else {
- ob.nums[ar[0]][1] += ar[1]
- }
- return ob
- }, { nums: {}, result: [] }).result
- .sort(function (a, b) {
- return new Date(a[0]) - new Date(b[0]);
- });
- $('body').append(JSON.stringify(result));
- });
- </script>
- </head>
- <body>
- </body>
- </html>
[["01/01/2015",10],["01/02/2015",9],["01/03/2015",15],["01/04/2015",1],["01/05/2015",5],["01/06/2015",4],["01/07/2015",11],["01/08/2015",8],["01/10/2015",3]]
You can see "01/01/2015" is not in array1 so it will add and "01/05/2015" exist in both arrays so new value should be the sum of both array values.

Join the conversation! Your thoughts help the community grow.