Using reduce() to eliminate duplicate keys os an array of objects and get its total values

PHOTO EMBED

Thu Apr 28 2022 08:54:52 GMT+0000 (Coordinated Universal Time)

Saved by @jen_magpantay #javascript

// considering this array of objects
const orders = [
  {
    id: 101,
    server: "Mindy Kaling",
    subtotal: 473,
    tax: 24,
  },
  {
    id: 102,
    server: "Nina Totenberg",
    subtotal: 1053,
    tax: 52,
  },
  {
    id: 103,
    server: "Serena Williams",
    subtotal: 1497,
    tax: 75,
  },
  {
    id: 104,
    server: "Mindy Kaling",
    subtotal: 251,
    tax: 12,
  },
  {
    id: 105,
    server: "Malala Yousafzai",
    subtotal: 1715,
    tax: 85,
  },
  {
    id: 106,
    server: "Nina Totenberg",
    subtotal: 320,
    tax: 16,
  },
];

// we have to check if there is any duplicate entry on the list
// create an objet to hold all the servers
// use reduce by passing two params: the new object and orders
function renderByServers(orders) {
    const servers = {};

    const result = orders.reduce((servers, order) => {
      const { server, subtotal, tax } = order;

      // first, check if the server is undefined: if yes, set it to 0
      // if(servers[server] === undefined){}
      if (!servers[server]) {
        servers[server] = 0;
      }
      // otherwise, calculate the reduce by adding to the server the sum of subtotal + tax
      servers[server] += subtotal + tax;
      return servers;
    }, {});

    return result;
  }
  // this function returns an object - that is not possible to use .map() once map is for arrays
  // also, an object cannot be passed by as children
  console.log(renderByServers(orders));

  // but is possible to get the keys or values of the object converted in array, and from there, map() if is necessary
  console.log(Object.keys(renderByServers(orders)));
  console.log(Object.values(renderByServers(orders)));
content_copyCOPY