I am trying to plot a chart to display sales comparison by year for the brands, below are the two arrays of sales by year.
var current_year = [
{
total: 12941.17,
comapanyName: "Samsung",
year: "2021"
},
{
total: 17946.87,
comapanyName: "Haier",
year: "2021"
},
{
total: 3832.36,
comapanyName: "Beetel",
year: "2021"
},
{
total: 12528,
comapanyName: "Celkon",
year: "2021"
}
];
var last_year = [
{
total: 427805.51,
comapanyName: "Samsung",
year: "2020"
},
{
total: 77576.33,
comapanyName: "Godrej",
year: "2020"
},
{
total: 53389.02,
comapanyName: "Beetel",
year: "2020"
},
{
total: 100748.49,
comapanyName: "Celkon",
year: "2020"
},
{
total: 4534.19,
comapanyName: "FORD",
year: "2020"
},
{
total: 5.05,
comapanyName: "Voltas",
year: "2020"
}
];
Since some company names are missing in respective arrays I'm not able to plot the chart as expected. I need help in adding the missing company name in respective array with year, name and total. Similar to this chart https://apexcharts.com/react-chart-demos/line-charts/data-labels/
Expectation -
- company "FORD" is present in last_year but missing in current_year array, Add the "FORD" Object in current_year array Example = [{total:0, comapnyName:'FORD', year:2021}]
- company "Haier" is present in current_year but missing in last_year array, Add the "Haier" in last_year array Example = [{total:0, comapnyName:"Haier", year:2020}]
CodePudding user response:
here is an example that can help you
var current_year = [
{
total: 12941.17,
comapanyName: "Samsung",
year: "2021"
},
{
total: 17946.87,
comapanyName: "Haier",
year: "2021"
},
{
total: 3832.36,
comapanyName: "Beetel",
year: "2021"
},
{
total: 12528,
comapanyName: "Celkon",
year: "2021"
}
];
var last_year = [
{
total: 427805.51,
comapanyName: "Samsung",
year: "2020"
},
{
total: 77576.33,
comapanyName: "Godrej",
year: "2020"
},
{
total: 53389.02,
comapanyName: "Beetel",
year: "2020"
},
{
total: 100748.49,
comapanyName: "Celkon",
year: "2020"
},
{
total: 4534.19,
comapanyName: "FORD",
year: "2020"
},
{
total: 5.05,
comapanyName: "Voltas",
year: "2020"
}
];
const currentYearData = {};
for (const item of current_year) {
currentYearData[item.comapanyName] = true;
}
for (const item of last_year) {
if (!currentYearData.hasOwnProperty(item.comapanyName) && item.comapanyName) {
// Company exists in last_year but not in current_year
current_year.push({ total: 0, companyName: item.comapanyName, year: "2021" });
}
}
for (const item of current_year) {
if (!last_year.find(c => c.comapanyName === item.comapanyName) && item.comapanyName) {
// Company exists in current_year but not in last_year
last_year.push({ total: 0, companyName: item.comapanyName, year: "2020" });
}
}
console.log(current_year);
console.log(last_year);