Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Last active January 7, 2020 00:16
Show Gist options
  • Save Woodsphreaker/9122f974df0d19b65fce4f4e8572822a to your computer and use it in GitHub Desktop.
Save Woodsphreaker/9122f974df0d19b65fce4f4e8572822a to your computer and use it in GitHub Desktop.
Flatten Results
const arrObj = [
//Primeiro elemento
[
{
"name": "Distri Equipamente Cirurgicos",
"data": 18
},
{
"name": "DNAPet",
"data": 70
}
],
//Secundo elemento
[
{
"name": "Distri Equipamente Cirurgicos",
"data": 62
},
{
"name": "Medical Pet&Thingss",
"data": 184
},
{
"name": "DNAPet",
"data": 251.2
}
],
//Terceiro elemento
[
{
"name": "DNAPet",
"data": 2087.1
}
],
//Quarto elemento
[
{
"name": "Medical Pet&Thingss",
"data": 80
}
]
]
const getUniqueKeys = (obj) =>
[].concat(...obj)
.reduce((acc, cur) =>
acc.add(cur.name),
new Set())
const makeObj = (objSize, ...keys) => {
return keys.reduce((acc, cur) =>
acc.concat({
name: cur,
data: Array(objSize).fill(null)
}), [])
}
const flatten = (obj) =>
[].concat(...obj)
.reduce((acc, cur, index) => {
acc[0].find(key => key.name === cur.name).data.splice(acc[1], 1, cur.data)
if (obj[acc[1]].length + acc[2] === index + 1) {
acc[2] += obj[acc[1]].length
acc[1]++
}
return acc
}, [makeObj(obj.length, ...getUniqueKeys(obj)), 0, 0])[0]
console.log(flatten(arrObj))
/*
[ { name: 'Distri Equipamente Cirurgicos', data: [ 18, 62, null, null ] },
{ name: 'DNAPet', data: [ 70, 251.2, 2087.1 , null] },
{ name: 'Medical Pet&Thingss', data: [ null,184, null, 80 ] } ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment