Reputation: 2675
I am creating a sunburst chart in highcharts and I am having trouble creating layers in the array.
For instance, the headers array is layer 2 and data array is layer 3.
I need to compare the headername with groups from data and create a new array giving both a child id and a parent id.
Have posted my current solution below the code.
const headers = ['Cars', 'Fruits', 'Food'];
const data = [{
group: 'Cars',
name: 'BMW',
value: '25641'
}, {
group: 'Fruits',
name: 'Apple',
value: '45876'
},
{
group: 'Cars',
name: 'Benz',
value: '65784'
},
{
group: 'Cars',
name: 'Toyota',
value: '254'
},
{
group: 'Food',
name: 'Pizza',
value: '87535'
},
{
group: 'Cars',
name: 'Honda',
value: '65796'
},
{
group: 'Fruits',
name: 'Banana',
value: '98631'
},
{
group: 'Fruits',
name: 'Orange',
value: '87563'
},
{
group: 'Food',
name: 'Burger',
value: '78324'
},
{
group: 'Fruits',
name: 'Mango',
value: '24598'
}
]
This is what I tried.
const newArray = headers.map(function(itemA, indexA) {
return data.map(function(itemB, indexB) {
return {
id: `3.${indexB + 1}`,
parentId: `2.${indexA + 1}`,
value: itemB.value,
name: itemB.name
}
})
})
This is the output I expect:
const newArray = [{
id: '3.1',
parentId: '2.1',
name: 'BMW',
value: '25641'
}, {
id: '3.2',
parentId: '2.2',
name: 'Apple',
value: '45876'
},
{
id: '3.3',
parentId: '2.1',
name: 'Benz',
value: '65784'
},
{
id: '3.4',
parentId: '2.1'
name: 'Toyota',
value: '254'
},
{
id: '3.5',
parentId: '2.3',
name: 'Pizza',
value: '87535'
},
{
id: '3.6',
parentId: '2.1',
name: 'Honda',
value: '65796'
},
{
id: '3.7',
parentId: '2.2',
name: 'Banana',
value: '98631'
},
{
id: '3.8',
parentId: '2.2',
name: 'Orange',
value: '87563'
},
{
id: '3.9',
parentId: '2.3',
name: 'Burger',
value: '78324'
},
{
id: '3.10',
parentId: '2.2',
name: 'Mango',
value: '24598'
}
]
Upvotes: 0
Views: 38
Reputation: 92440
You don't need the nested maps — it will cause nested arrays of results. You just need one because there is a 1-to1 relationship between data
and your expected output. You can just map()
over data and lookup the parent index as you go.
const headers = ['Cars', 'Fruits', 'Food'];
const data = [{group: 'Cars',name: 'BMW',value: '25641'}, {group: 'Fruits',name: 'Apple',value: '45876'},{group: 'Cars',name: 'Benz',value: '65784'},{group: 'Cars',name: 'Toyota',value: '254'},{group: 'Food',name: 'Pizza',value: '87535'},{group: 'Cars',name: 'Honda',value: '65796'},{group: 'Fruits',name: 'Banana',value: '98631'},{group: 'Fruits',name: 'Orange',value: '87563'},{group: 'Food',name: 'Burger',value: '78324'},{group: 'Fruits',name: 'Mango',value: '24598'}]
const newArray = data.map(function(itemB, indexB) {
let parentIndex = headers.indexOf(itemB.group) // just find the parent index
return {
id: `3.${indexB + 1}`,
parentId: `2.${parentIndex + 1}`,
value: itemB.value,
name: itemB.name
}
})
console.log(newArray)
Upvotes: 1