DEV Community

Discussion on: Merging array tables in JS

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