Home > Software design >  Array of Objects
Array of Objects

Time:10-21

Hey guys I hope someone can help me. I've got array of objects

const users = [
  {
    id: "2222",
    name: "Peter",
    age: 20,
    carts: [
      {
        productId: "1a3va",
        price: 3.44,
        quantity: 3,
      },
      {
        productId: "3adf4",
        price: 8.44,
        quantity: 5,
      },
    ],
  },
  {
    id: "43443",
    name: "John",
    age: 24,
    carts: [
      {
        productId: "2334a",
        price: 13.44,
        quantity: 13,
      },
      {
        productId: "4234d",
        price: 1.44,
        quantity: 1,
      },
    ],
  },
];

Then my task is for function invoiceCustomer -> return the total value of items in the cart, for a given customer with suggested parameters. And for totalOrderValue it should return the total value of the order.

function invoiceCustomer(users, id, name, age) {}
function totalOrderValue(order) {}

I have experimented with map and reduce but getting NaN error even if I use parseInt.

I hope that someone can help me with this. Thanks!

CodePudding user response:

I think this should work.

function totalOrderValue(users, id, name, age) {
  let user = users.filter( (item, index, array) => {
     // Used only one criteria (id) for example simplicity
     return item.id === id;
  });
  if (user.length === 1) {
     return user[0].carts.reduce((prevValue, item) => {
       return prevValue   (item.price * item.quantity);
     }, 0); // Important: initialize prevValue to 0
  } else if (user.length === 0) {
     throw 'User not found';
  } else {
     throw 'Too many users found';
  }

}

I can't help you with the totalOrderValue function cause there's no orderId to filter the data, but you get the point of using filter and reduce methods.

  • Related