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]


== Sort Objects by a Property ==
== 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 lang="shell" class="code-continue">
</syntaxhighlight>
sort.ts
 
</syntaxhighlight><syntaxhighlight lang="typescript" class="code-continue">
== 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

Ref­er­ences

Da­ta file of the ex­am­ples

data.mjs
export default [
    { product: "#1", price: 7.54 },
    { product: "#2", price: 2.55 },
    { product: "#3", price: 3.79 }
];

Sort Ob­jects by a Prop­er­ty (Price)

import products from "./data.mjs";

function sortProducts(data: { product: string, price: number }[]) {
    return data.sort((a, b) => a.price - b.price);
}

Re­duce the prices in­to 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);
}