Merge 2 Arrays and Sum the Values (Numeric Keys)

Merge 2 Arrays and Sum the Values (Numeric Keys)

This actual calculation can be done in 2 lines of code, no need for loops:

http://codepad.viper-7.com/ieSkHQ

$arr1 = array('amount1' => 1, 'amount2' => 6);
$arr2 = array('amount1' => 2, 'amount2' => 7);
$add = function($a, $b) { return $a + $b; };
$summedArray = array_map($add, $arr1, $arr2);
print_r($summedArray);

Youl'll just need to make the appropriate adjustment to account for you nested structure.

How to merge two arrays and sum the values of duplicate keys?

I think the problem is simpler than it looks. You really only need a conditional to preclude undefined offset notices. Just iterate all keys and values in both arrays and add the values to the corresponding key in the merged array.

foreach ([$a1, $a2] as $a) {                             // iterate both arrays
foreach ($a as $key => $value) { // iterate all keys+values
$merged[$key] = $value + ($merged[$key] ?? 0); // merge and add
}
}

Really, the line that actually does the addition ($merged[$key] = $value + ($merged[$key] ?? 0);) could be reduced to $merged[$key] += $value;. That would still work, but it would produce a bunch of undefined offset notices. So instead we can set the key equal to the value plus either the previous value (if it exists) or zero.

If you're still using PHP 5, you can use a ternary instead of the null coalescing operator (??), like this:

$merged[$key] = $value + (isset($merged[$key]) ? $merged[$key] : 0);

The output won't be in the same order shown in your desired result, but you can use ksort($merged); to accomplish that

How to merge two arrays of objects, and sum the values of duplicate object keys in JavaScript?

The following matches the commented array at top of question. Expected results are a little unclear

Using Object.keys() makes it fairly easy.

var demo = {    "key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}],    "key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}]};
// iterate and map using first arrayvar res = demo.key1.map(function(item, idx) { // loop over keys of each object in array and return // new objects with sums of matching index and keys return Object.keys(item).reduce(function(obj,key) { obj[key] = item[key] + demo.key2[idx][key]; return obj; },{}); });
// print "res" for demodocument.getElementById('pre').innerHTML =JSON.stringify(res, null, 4)
<pre id="pre"></pre>

Javascript merge 2 arrays and sum same key values

This is one way to do it:

var sums = {}; // will keep a map of number => sum

// for each input array (insert as many as you like)
[array1, array2].forEach(function(array) {
//for each pair in that array
array.forEach(function(pair) {
// increase the appropriate sum
sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
});
});

// now transform the object sums back into an array of pairs
var results = [];
for(var key in sums) {
results.push([key, sums[key]]);
}

See it in action.

How to merge two arrays and sum values of duplicate objects using lodash

You can do it with plain JavaScript.

Use Array.reduce() to make an intermediate dictionary by id and accumulate the quantities, then turn it into an array with Object.values():

const arr1 = [  {"id": "5c5030b9a1ccb11fe8c321f4", "quantity": 1},  {"id": "344430b94t4t34rwefewfdff", "quantity": 5},  {"id": "342343343t4t34rwefewfd53", "quantity": 3}];const arr2 = [  {"id": "5c5030b9a1ccb11fe8c321f4", "quantity": 2},  {"id": "344430b94t4t34rwefewfdff", "quantity": 1}];
const result = Object.values([...arr1, ...arr2].reduce((acc, { id, quantity }) => { acc[id] = { id, quantity: (acc[id] ? acc[id].quantity : 0) + quantity }; return acc;}, {}));
console.log(result);

PHP7: Combine two arrays, where one is key and second is value (integer), sum values for duplicate keys

The code you need is as easy as that:

// The input arrays
$Array1 = ['bus', 'bus', 'int'];
$Array2 = [2, 18, 10];

// Build the result here
$Array3 = [];

// There is no validation, the code assumes that $Array2 contains
// the same number of items as $Array1 or more
foreach ($Array1 as $index => $key) {
// If the key $key was not encountered yet then add it to the result
if (! array_key_exists($key, $Array3)) {
$Array3[$key] = 0;
}

// Add the value associate with $key to the sum in the results array
$Array3[$key] += $Array2[$index];
}

print_r($Array3);

Its output:

Array
(
[bus] => 20
[int] => 10
)

PHP: merge two arrays while keeping keys instead of reindexing?

You can simply 'add' the arrays:

>> $a = array(1, 2, 3);
array (
0 => 1,
1 => 2,
2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
'a' => 1,
'b' => 2,
'c' => 3,
)
>> $a + $b
array (
0 => 1,
1 => 2,
2 => 3,
'a' => 1,
'b' => 2,
'c' => 3,
)

Combining two multidimensional arrays and sum only one key w/ numerical value - PHP

This will recursively merge two arrays and apply a callback to determine what to do with matching-key non-array values.

function array_merge_map_recursive($r1, $r2, $callback) {
$merged = array();
foreach ($r1 as $k => $v) {
if (!isset($r2[$k])) {
$merged[$k] = $v;
}
elseif (!is_array($v)) {
$merged[$k] = $callback($k,$v,$r2[$k]);
}
else {
$merged[$k] = array_merge_map_recursive($v,$r2[$k],$callback);
}
}
return $merged;
}

The callback will sum the two elements if the key is 'value', otherwise if they're the same it will leave it alone, and if they're not the same it will wrap them in an array. If you want to sum any numerical values, regardless of key, you can change the first if to something like if (is_numeric($v1)).

This syntax requires PHP 5.3, but it can be rewritten for earlier versions pretty easily.

$sumIfValue = function($key,$v1,$v2) {
if ($key==='value') {
return $v1 + $v2;
} elseif ($v1===$v2) {
return $v1;
} else {
return array($v1,$v2);
}
};

Then you can call it like this (where your two arrays are $array1 and $array2):

$merged = array_merge_map_recursive($array1, $array2, $sumIfValue);

Merge or sum 2 arrays on keys in ruby

You could do it thusly:

(a + b).group_by(&:first).map { |k, v| [k, v.map(&:last).inject(:+)] }

First you put the arrays together with + since you don't care about a and b, you just care about their elements. Then the group_by partitions the combined array by the first element so that the inner arrays can easily be worked with. Then you just have to pull out the second (or last) elements of the inner arrays with v.map(&:last) and sum them with inject(:+).

For example:

>> a = [[1,10],[2,20],[3,30]]
>> b = [[1,50],[3,70]]
>> (a + b).group_by(&:first).map { |k,v| [k, v.map(&:last).inject(:+)] }
=> [[1, 60], [2, 20], [3, 100]]


Related Topics



Leave a reply



Submit