Home > Enterprise >  JavaScript trying to find the highest sales made in a particular branch
JavaScript trying to find the highest sales made in a particular branch

Time:01-29

I am trying to create a class to find out the branch made the most in revenue.I believe, I need to sum all branch across multiple days and identify which branch had the highest sales overall. But I am kinda lost. Would anyone be able to help me? Thanks for the help

class SalesItem {
    constructor(branch, totalSales, date) {
        this.branch = branch;
        this.totalSales = totalSales;
        this.date = date
    }
}

function CalculateBestBranch(sales) {
var branchSales = { key: "", value: 0 };



// TODO: order branchSales by value, highest first
// TODO: return the key of the highest value
const highestValue = 0;
return highestValue;

}

CodePudding user response:

class SalesItem {
  constructor(branch, totalSales, date) {
    this.branch = branch;
    this.totalSales = totalSales;
    this.date = date;
  }
}

const sales = [
  new SalesItem('branch-1', 60, '2022-01-26'),
  new SalesItem('branch-2', 90, '2022-01-26'),
  new SalesItem('branch-1', 20, '2022-01-27'),
  new SalesItem('branch-2', 30, '2022-01-27'),
];

function calculateBestBranch(sales) {
  const branchSales = [];

  sales.forEach((sale) => {
    if (!branchSales.find((e) => e.key === sale.branch)) {
      branchSales.push({ key: sale.branch, value: sale.totalSales });
    } else {
      let i = branchSales.findIndex((e) => e.key == sale.branch);
      branchSales[i].value  = sale.totalSales;
    }
  });

  const sortedBranchSales = branchSales.sort((a, b) => b.value - a.value);

  return sortedBranchSales[0];
}

calculateBestBranch(sales); // { key: 'branch-2', value: 120 }
  •  Tags:  
  • Related