0

Given an array of arrays, how do I convert this to a JavaScript object with the condition that the first element of each array of the internal arrays will be a key of a new JavaScript object, the subsequent element would be the value?

And if there is more than one occurrence of the element in the first position of the internal arrays only create a single key corresponding to this element.

For example:

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]

should return:

var obj = {a: ["b", "e"], c: ["d"]}

Here there are 2 occurrences of a within arr therefore only a single key a was created in obj along with c

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Caleb Oki
  • 667
  • 2
  • 11
  • 29

2 Answers2

2

Using Array.prototype.reduce function, you can accomplish this as follows.

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']];

const output = arr.reduce((acc, cur) => {
  acc[cur[0]] ? acc[cur[0]].push(cur[1]) : acc[cur[0]] = [ cur[1] ];
  return acc;
}, {});
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
2

This is an alternative:

var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
const obj = {}
arr.forEach(([k, v]) => obj[k] = [...obj[k] ?? [], v])

  • unless the inner arrays are longer than 2, in which case `arr.forEach(([k, ...v]) => obj[k] = [...obj[k] ?? [], ...v])` – pilchard Nov 07 '20 at 22:52