I want to join values of array by key to another array. For example, for below input array
[['value', 'element1'],['value', 'element2'], ['value1', 'element1'], ['value', null]]
I would like to have an output
[['value', 'element1', 'element2'], ['value1', 'element1']]
Is there any way to achieve this?
A simple reduce on the data can solve this. Often you would use an object to map the values to keys, and then map out the key/values to a new array, but in this case you can just use an index to target a nested array in the returned array instead.
var out = data.reduce(function (p, c) {
// the key is the first array element, the value the second
// and i is the index of the nested array in the returned array
var key = c[0],
val = c[1],
i = +key.substr(5) || 0;
// if the nested array in the returned array doesn't exist
// create it as a new array with the key as the first element
p[i] = p[i] || [key];
// if the value is not null, push it to the correct
// nested array in the returned array
if (val) p[i].push(val);
return p;
}, []);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With