This fixes a problem with the accepted answer when you have multi levelled sankey diagram
Refer to original answer for calculating "sourceTotals" and "destTotals"
assume I have some arr "chart" with multi levelled sankey diagram data
this.chart = {
type: 'Sankey',
title: '',
data: [
[ 'USA', 'Mexico', 15 ],
[ 'USA', 'Brazil', 16 ],
[ 'South America', 'Mexico', 4 ],
[ 'South America', 'Brazil', 4 ],
[ 'Jamaica', 'Mexico', 18 ],
[ 'South Africa', 'Brazil', 2 ],
[ 'England', 'Brazil', 9 ],
[ 'England', 'Mexico', 9 ],
[ 'Mexico', 'Japan', 4 ],
[ 'Mexico', 'North Pole', 4 ],
[ 'China', 'Denmark', 5 ],
[ 'China', 'Canada', 7 ],
[ 'Mexico', 'China', 10 ],
],
}
First off delete destination keys that appear in sourceTotals Object
for (const key in destTotals) {
if (destTotals.hasOwnProperty(key)) {
if (sourceTotals.hasOwnProperty(key)) {
delete sourceTotals[key];
}
}
}
isKeyInObject(query, object) {
for (const key in object) {
if (object.hasOwnProperty(query)) {
return true;
}
}
return false;
}
this.chart.data.forEach( (d) => {
// Check if d[0] key is in source totals
if (this.isKeyInObject(d[0], sourceTotals)) {
d[0] = d[0] + ' (' + sourceTotals[d[0]] + ')';
}
// check of d[1] key exists in dest totals
if (this.isKeyInObject(d[1], destTotals)) {
d[1] = '(' + destTotals[d[1]] + ') ' + d[1];
}
// deal with destination keys in source index in original arr
// check if key in position 0 of original chart data is available in destTotals object
// change its name to the name key in destTotals
if (this.isKeyInObject(d[0], destTotals)) {
console.log('POS_ZERO_IN_DEST', d[0]);
d[0] = '(' + destTotals[d[0]] + ') ' + d[0];
}
});