Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join value of js array by key

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?

like image 794
Lukaszaq Avatar asked Jan 27 '26 00:01

Lukaszaq


1 Answers

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

like image 79
Andy Avatar answered Jan 28 '26 16:01

Andy