Home > Back-end >  Converting Array of Pairs into 2 Separate Arrays Without Iteration
Converting Array of Pairs into 2 Separate Arrays Without Iteration

Time:10-24

I have an array of pairs that looks like this [[x,y], [x,y] ... ]. I want to format it into an Object where the values are arrays of x and y values like so {keys: [x1, x2, x3 ...], values: [y1, y2, y3 ... ]}.

Are there any array/object operations to complete this operation without iterating through the original list?

CodePudding user response:

Building on top of pilchard's answer, I would convert the array to a Map, and then take the Map's keys, and values. I would use a Map, and not an object, because object's keys are always strings, and if the values are integers, the object would also be sorted by their value. A Map would preserve the original type, and won't reorder them.

const input = [[3, 300], [4, 200], [1, 100]];

const map = new Map(input);
const result = { keys: [...map.keys()], values: [...map.values()] };

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

An example of converting the same structure to an object:

const input = [[3, 300], [4, 200], [1, 100]];

const obj = Object.fromEntries(input);
const result = { keys: Object.keys(obj), values: Object.values(obj) };

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The process is iterative, but you can hide it by using existing Object methods: Object.fromEntries(), Object.keys(), Object.values()

const input = [['a', 1], ['b', 2], ['c', 3]];

const obj = Object.fromEntries(input);
const result = { keys: Object.keys(obj), values: Object.values(obj) };

console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Ori Drori's refinement using a Map is more robust not only for numeric values but for any type.

const input = [[new Date(), { y: 1 }], [new Date(), { y: 2 }], [new Date(), { y: 3 }]];

const map = new Map(input);
const result = { keys: [...map.keys()], values: [...map.values()] };

console.log(result);
console.log(result.keys[0].valueOf());
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

No space left for losers, but just another way

const input = [[3, 300], [4, 200], [1, 100]];
const result = { keys: Array.from(input, x => x[0]), values: Array.from(input, x => x[1]) };
console.log(result);
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related