DEV Community

Cover image for Merging array tables in JS
Marc Garcia i Mullon
Marc Garcia i Mullon

Posted on

Merging array tables in JS

Problem

We need to merge all this arrays into one big object.
First line of every array is the table headings, followed by users data.

  const arr1 = [
    ["name", "id", "age", "weight", "Cool"],
    ["Susan", "3", "20", "120", true],
    ["John", "1", "21", "150", true],
    ["Bob", "2", "23", "90", false],
    ["Ben", "4", "20", "100", true],
  ];

  const arr2 = [
    ["name", "id", "height"],
    ["Bob", "2", "50"],
    ["John", "1", "45"],
    ["Ben", "4", "43"],
    ["Susan", "3", "48"]
  ];

  const arr3 = [
    ["name", "id", "parent"],
    ["Bob", "2", "yes"],
    ["John", "1", "yes"]
  ];
Enter fullscreen mode Exit fullscreen mode

My proposal:

const data = {};

function addData(arr, uuid = 'id'){
    const [headings, ...body] = arr;
    for(const elem of body){
        let id;
        let person = {};
        for(const [index, heading] of headings.entries()){
            if(heading === uuid){
                id = elem[index];
            }
            person[heading] = elem[index];
        }
        data[id] = {...data[id], ...person};
    }
}

addData(arr1);
addData(arr2);
addData(arr3);
console.table(data);
Enter fullscreen mode Exit fullscreen mode

Can you improve it? Do you have a different solution?
Let me know in comments!

Top comments (1)

Collapse
 
drarig29 profile image
Corentin Girard

I used the same names for variables. I don't like messing with global variables very much, so I made a makeData() function, which is a pure function.

Then I made a replacement addData() function to have the same functionality as your code. You can use it the same way 😄

function makeData(arr, uuid = 'id') {
    const [headings, ...body] = arr;
    const idPosition = headings.indexOf(uuid);

    return body.reduce((data, elem) => ({
        ...data, ...{
            [elem[idPosition]]: Object.fromEntries(elem.map((value, index) => [headings[index], value]))
        }
    }), {});
}

function addData(arr, uuid = 'id') {
    Object.assign(data, makeData(arr, uuid));
}
Enter fullscreen mode Exit fullscreen mode