JS Snippets: Array of Objects: Difference between revisions
From WikiMLT
m (Стадий: 6 [Фаза:Утвърждаване, Статус:Утвърден]; Категория:JavaScript) |
|||
Line 5: | Line 5: | ||
*[https://github.com/metalevel-tech/exc-js-homework MLT GitHub: JavaScript Homework Tasks] | *[https://github.com/metalevel-tech/exc-js-homework MLT GitHub: JavaScript Homework Tasks] | ||
== | == Data file of the examples == | ||
<syntaxhighlight lang="shell" class="code-continue"> | <syntaxhighlight lang="shell" class="code-continue"> | ||
data.mjs | data.mjs | ||
Line 14: | Line 14: | ||
{ product: "#3", price: 3.79 } | { product: "#3", price: 3.79 } | ||
]; | ]; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Sort Objects by a Property (Price) == | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
import products from "./data.mjs"; | import products from "./data.mjs"; | ||
function sortProducts(data: { product: string, price: number }[]) { | function sortProducts(data: { product: string, price: number }[]) { | ||
return data.sort((a, b) => a.price - b.price); | return data.sort((a, b) => a.price - b.price); | ||
} | |||
</syntaxhighlight> | |||
== Reduce the prices into a Sum == | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
import products from "./data.mjs"; | |||
function sortProducts(data: { product: string, price: number }[]) { | |||
return parseFloat( | |||
data.reduce((acc, { price }) => acc + price, 0) | |||
).toFixed(2); | |||
} | } | ||
</syntaxhighlight><noinclude> | </syntaxhighlight><noinclude> |
Revision as of 13:57, 11 March 2023
References
Data file of the examples
data.mjs
export default [
{ product: "#1", price: 7.54 },
{ product: "#2", price: 2.55 },
{ product: "#3", price: 3.79 }
];
Sort Objects by a Property (Price)
import products from "./data.mjs";
function sortProducts(data: { product: string, price: number }[]) {
return data.sort((a, b) => a.price - b.price);
}
Reduce the prices into a Sum
import products from "./data.mjs";
function sortProducts(data: { product: string, price: number }[]) {
return parseFloat(
data.reduce((acc, { price }) => acc + price, 0)
).toFixed(2);
}