I have been trying to convert the following code
{
0: {
host: 'first'
date: '2021-04-03'
first_count: 12
second_count: 10
}
1: {
host: 'first'
date: '2021-04-02'
first_count: 10
second_count: 8
}
2: {
host: 'first'
date: '2021-04-01'
first_count: 23
second_count: 30
}
}
into
{
0: {
host: 'first'
first_count_array: {
0: {
date: '2021-04-03'
first_count: 12
}
1: {
date: '2021-04-02'
first_count: 10
}
2: {
date: '2021-04-01'
first_count: 23
}
}
second_count_array: {
0: {
date: '2021-04-03'
second_count: 10
}
1: {
date: '2021-04-02'
second_count: 8
}
2: {
date: '2021-04-01'
second_count: 30
}
}
}
}
without using nested loops.
I have tried foreach loop but it involves nested loops and n^2 complexity. I want to know if there is a way to perform this action without using nested loops and less than n^2 complexity.
I recommend using reducer which would reduce your array to Map then get the entries as an array You can try this code on you chrome console
Comlexity : O(n)
var data = [{host: 'first', date: '2021-04-03', first_count: 12, second_count: 10}, {
host: 'first',
date: '2021-04-02',
first_count: 10,
second_count: 8
}, {
host: 'first', date: '2021-04-01', first_count: 23, second_count: 30
}];
mapData = data.reduce((map, currentValue) =>
map.has(currentValue.host) ?
map.set(currentValue.host,
{host: currentValue.host,
first_count_array: [...map.get(currentValue.host).first_count_array, {date: currentValue.date, first_count: currentValue.first_count}],
second_count_array: [...map.get(currentValue.host).second_count_array, {date: currentValue.date, second_count: currentValue.second_count}]} )
:
map.set(currentValue.host, {
host: currentValue.host,
first_count_array: [{date: currentValue.date, first_count: currentValue.first_count}],
second_count_array: [{date: currentValue.date, second_count: currentValue.second_count}]
})
,
new Map()
);
console.log(Array.from(mapData.values()));