Home > Mobile >  Merge arrays based on first value within each array
Merge arrays based on first value within each array

Time:11-23

I have an array that looks like this:

var arr = [
[
    "2021-07-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787"
],
[
    "2021-08-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787"
],
[
    "2021-07-31T00:00:00Z",
    "AAAA"
],
[
    "2021-08-31T00:00:00Z",
    "BBBB"
]

]

I'd like to transform this based on the first value (the date) of each array. So if the dates match they will merge into one. So the output I'm trying to get is

[
[
    "2021-07-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787",
    "AAAA"
],
[
    "2021-08-31T00:00:00Z",
    "648429a0-00e5-4752-9d84-2857a0ea0787",
     "BBBB"
]

]

Would be grateful to know what would be the best approach in this instance.

CodePudding user response:

Use a map to overwrite the values as they are found in the array. Then use Object.entries() to create the final array:


var original = [ [1,2], [1,3], [2,3]]
var final = []
var map = {}

original.forEach(a => {
    if (!map[a[0]]) { map[a[0]] = [] }
    map[a[0]].push(a[1]);
});
Object.entries(map).forEach(e => final.push([e[0], ...e[1]]))

Edit: Changed the answer to get all the values

CodePudding user response:

You can try this reduce approach

    var arr = [
    [
        "2021-07-31T00:00:00Z",
        "648429a0-00e5-4752-9d84-2857a0ea0787"
    ],
    [
        "2021-08-31T00:00:00Z",
        "648429a0-00e5-4752-9d84-2857a0ea0787"
    ],
    [
        "2021-07-31T00:00:00Z",
        "AAAA"
    ],
    [
        "2021-08-31T00:00:00Z",
        "BBBB"
    ]
];

arr = arr.reduce((a, i) => {
    if (!a) a = [];
    var found = false;
    a.forEach(ai => {
        if (ai[0] == i[0]) {
            found = true;
            for (var k = 0; k < i.length; k  ) {
                if (k > 0)
                    ai.push(i[k]);
            }
        }
    });
    if (!found)
        a.push(i);
    return a;
}, []);
  • Related