Search code examples
javascriptarraysobject

Converting Array of Pairs into 2 Separate Arrays Without Iteration


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?


Solution

  • The easiest and safest way is to reduce the array to an object, although it requires a loop:

    const input = [[3, 300], [2, 200], [1, 100]];
    
    const result = input.reduce((acc, [key, val]) => {
      acc.keys.push(key);
      acc.values.push(val);
      
      return acc;
    }, { keys: [], values: [] });
    
    console.log(result);

    I wouldn't actually use the convert to object / Map method (under Original Answer), because it has a serious caveat - duplicate entries the has the same keys would be overridden.

    For example:

    const input = [[3, 300], [3, 200], [3, 100]];
    
    const obj = Object.fromEntries(input);
    const result = { keys: Object.keys(obj), values: Object.values(obj) };
    
    console.log(result);

    Original Answer

    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);

    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);