I have an array of invoice objects that I want to turn into a distinct array of just the supplier ID, supplier name and a reduced total across all the invoices from each distinct supplier where the status equals 3. Here is what I have so far:
const invoices = [
{
invoiceNumber: "12345678",
invoiceDate: "12th September 2023",
supplierId: "SUP123",
supplierName: "Roger Enterprises Ltd",
invoiceTotal: 1200,
status: 3
},
{
invoiceNumber: "87654321",
invoiceDate: "10th September 2023",
supplierId: "SUP123",
supplierName: "Roger Enterprises Ltd",
invoiceTotal: 800,
status: 1
},
{
invoiceNumber: "13572468",
invoiceDate: "8th September 2023",
supplierId: "SUP123",
supplierName: "Roger Enterprises Ltd",
invoiceTotal: 1000,
status: 3
},
{
invoiceNumber: "AB1234",
invoiceDate: "12th September 2023",
supplierId: "SUP456",
supplierName: "Steve Systems Ltd",
invoiceTotal: 500,
status: 3
},
{
invoiceNumber: "XY5678",
invoiceDate: "4th September 2023",
supplierId: "SUP456",
supplierName: "Steve Systems Ltd",
invoiceTotal: 700,
status: 3
}
]
Here is the desired output:
[
{
supplierId: "SUP123",
supplierName: "Roger Enterprises Ltd",
invoicesTotal: 2200
},
{
supplierId: "SUP456",
supplierName: "Steve Systems Ltd",
invoicesTotal: 1200
}
]
I’ve managed to piece together getting an array of distinct suppliers but am now stuck on how to reduce the relevant invoice totals from the original invoice array and insert that into the relevant supplier object in the arr array:
const distinctSupplierMap = new Map(
invoices.map((invoice) => [invoice.supplierId, invoice])
);
const distinctSuppliersFilter = [...distinctSupplierMap.values()];
let arr = [];
distinctSuppliersFilter.map((distSupp) => {
arr.push({
supplierId: distSupp.supplierId,
supplierName: distSupp.supplierName,
});
});
As always, any help is greatly appreciated
3
Answers
Use reduce like this:
You’ll want two steps
supplierId
in a map, only adding whenstatus === 3
You can first use
filter
to filter out the object where status is not3
then use reduce to create a an object where the key will be thesupplierId
. At the end useObject.values
to get an array out of the object