-
-
Save BrunoDSouza/3198f2f9ee251ea349c6c7a9af8db4a3 to your computer and use it in GitHub Desktop.
Flatten Results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arrObj = [ | |
//Primeiro element | |
[{ | |
"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 = (...keys) => | |
return keys.reduce((acc, cur) => | |
acc.concat({ | |
name: cur, | |
data: Array(objSize).fill(null) | |
}), []) | |
const addItem = (obj, comp) => | |
obj.map((item) => { | |
let result = comp.find(key => key.name === item.name) | |
if(result) item.data.push(result.data) | |
}) | |
const flatten = (obj) => | |
obj.reduce((acc, cur) => { | |
addItem(acc,cur) | |
return acc | |
}, makeObj(...getUniqueKeys(obj))) | |
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