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.
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
The OP's task can be achieved without nested iterations within a single reduce cycle.
The underlying approach is to use a tailored object as accumulator/collector. Such a collector features 2 properties ... index which serves as Object based map/lookup for grouped arrays where the group key is always the 1st item of each (to be) processed array ... and ... result which is going to hold references of the above mentioned (yet to be created) grouped arrays where one does always push the 2nd item of the currently processed array into.
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",
]];
function collectAndAggregateGroupedArrays(collector, item) {
const { index, result } = collector;
let groupKey = item[0];
let groupedList = index[groupKey];
if (!groupedList) {
groupedList = index[groupKey] = [groupKey];
result.push(groupedList);
}
groupedList.push(item[1]);
return collector;
}
console.log(
arr.reduce(collectAndAggregateGroupedArrays, {
index: {},
result: [],
}).result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
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;
}, []);