Does anyone have any suggestions for a better way to loop over an array of objects and add a new property called 'colors' based on the value of 'y'?
Although the function is working as expected, I keep encountering some compile errors.
This is the code I'm currently using:
interface IChartData {
name: string;
y ? : number;
isSum ? : boolean;
}
interface IColorChartByValue extends IChartData {
color: string;
}
const colorChartByValue = (
data: IChartData[]
): IColorChartByValue[] => {
return data.map((item: IChartData, index: number, array: IChartData[]) => {
if (index === 0 || index === array.length - 1) {
item.color = '#137cbd'
} else if (item.y >= 0) {
item.color = '#0F9960'
} else if (item.y < 0) {
item.color = '#D9822B'
}
return item;
});
};
const chartData: IChartData[] = [{
name: 'Base Case',
y: 100000,
},
{
name: 'Waterfall 1',
y: 11500,
},
{
name: 'Waterfall 2',
y: 5677,
},
{
name: 'Waterfall 3',
y: -3001,
},
{
name: 'Waterfall 4',
y: 6500,
},
{
name: 'Upside',
isSum: true,
},
]
console.log(colorChartByValue(chartData))
You can view the playground link here: Link
Your assistance is greatly appreciated. Thank you.