skip to Main Content

My task is to write a function that takes an object like the one below and deletes the "shelvesInCupboards" and "shelvesNotInCupboards" properties if they are present and adds a new property with their sum "totalShelves". I am not sure how to add my respective delete statements to get rid of the two mentioned properties without also altering my new "totalShelves" value.

Example object:

{
  shelvesInCupboards: 3,
  shelvesNotInCupboards: 2,
};
function sortTheKitchen(kitchen) {
    kitchen["totalShelves"] = 0;
    if (kitchen["shelvesInCupboards"] && kitchen["shelvesNotInCupboards"]) {
      totalShelves = kitchen["shelvesInCupboards"] + kitchen["shelvesNotInCupboards"]
    }
    if (kitchen["shelvesInCupboards"] && !kitchen["shelvesNotInCupboards"]) {
      totalShelves = kitchen["shelvesInCupboards"]
    }
    if (!kitchen["shelvesInCupboards"] && kitchen["shelvesNotInCupboards"]) {
      totalShelves = kitchen["shelvesNotInCupboards"]
    }
    return kitchen;
}

2

Answers


  1. It quite simple, just delete the property after you get the value totalShelves. And you should use nullish operator combine with optional chaining to simplify your function.

    function sortTheKitchen(kitchen) {
      kitchen["totalShelves"] =
        (kitchen?.shelvesInCupboards ?? 0) + (kitchen?.shelvesNotInCupboards ?? 0);
      delete kitchen.shelvesInCupboards;
      delete kitchen.shelvesNotInCupboards;
      return kitchen;
    }
    
    Login or Signup to reply.
  2. You can use Array::reduce() to sum any number of object properties and delete them simultaneously:

    const kitchen = {shelvesInCupboards: 2, shelvesNotInCupboards: 3};
    const kitchen2 = {shelvesInCupboards: 7};
    
    function sortTheKitchen(kitchen) {
      kitchen.totalShelves = ['shelvesInCupboards', 'shelvesNotInCupboards']
        .reduce((r, name) => (r += kitchen[name] ?? 0, delete kitchen[name], r), 0);
      return kitchen;
    }
    
    console.log(sortTheKitchen(kitchen));
    console.log(sortTheKitchen(kitchen2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search