JS Snippets: Array of Objects: Difference between revisions
From WikiMLT
Line 10: | Line 10: | ||
</syntaxhighlight><syntaxhighlight lang="javascript"> | </syntaxhighlight><syntaxhighlight lang="javascript"> | ||
export default [ | export default [ | ||
{ product: "#1", price: 7.54 }, | { product: "#1", type: "sweet", price: 7.54 }, | ||
{ product: "#2", price: 2.55 }, | { product: "#2", type: "savory", price: 2.55 }, | ||
{ product: "#3", price: 3.79 } | { product: "#3", type: "savory", price: 3.79 } | ||
]; | ]; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 20: | Line 20: | ||
import products from "./data.mjs"; | import products from "./data.mjs"; | ||
function sortProducts(data: { product: string, price: number }[]) { | function sortProducts(data: { product: string, type: string, price: number }[]) { | ||
return data.sort((a, b) => a.price - b.price); | return data.sort((a, b) => a.price - b.price); | ||
} | } | ||
Line 29: | Line 29: | ||
import products from "./data.mjs"; | import products from "./data.mjs"; | ||
function | function sumPrices(data: { product: string, type: string, price: number }[]) { | ||
return parseFloat( | return parseFloat( | ||
data.reduce((acc, { price }) => acc + price, 0) | data.reduce((acc, { price }) => acc + price, 0) | ||
).toFixed(2); | |||
} | |||
</syntaxhighlight> | |||
== Reduce the prices of certain product type into a Sum == | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
import products from "./data.mjs"; | |||
function sumPrices(data: { product: string, type: string, price: number }[]) { | |||
return parseFloat( | |||
data | |||
.filter(({ type }) => type === "savory") | |||
.reduce((acc, { price }) => acc + price, 0) | |||
).toFixed(2); | ).toFixed(2); | ||
} | } |
Revision as of 14:04, 11 March 2023
References
Data file of the examples
data.mjs
export default [
{ product: "#1", type: "sweet", price: 7.54 },
{ product: "#2", type: "savory", price: 2.55 },
{ product: "#3", type: "savory", price: 3.79 }
];
Sort Objects by a Property (Price)
import products from "./data.mjs";
function sortProducts(data: { product: string, type: string, price: number }[]) {
return data.sort((a, b) => a.price - b.price);
}
Reduce the prices into a Sum
import products from "./data.mjs";
function sumPrices(data: { product: string, type: string, price: number }[]) {
return parseFloat(
data.reduce((acc, { price }) => acc + price, 0)
).toFixed(2);
}
Reduce the prices of certain product type into a Sum
import products from "./data.mjs";
function sumPrices(data: { product: string, type: string, price: number }[]) {
return parseFloat(
data
.filter(({ type }) => type === "savory")
.reduce((acc, { price }) => acc + price, 0)
).toFixed(2);
}