JS Snippets: Array of Objects: Difference between revisions

From WikiMLT
Line 58: Line 58:
             .map(({ item, price }) => ({ item, price }));
             .map(({ item, price }) => ({ item, price }));
}
}
</syntaxhighlight><noinclude>
</syntaxhighlight><noinclude><div id='devStage'>
<div id='devStage'>
{{devStage  
{{devStage  
  | Прндл  = JavaScript
  | Прндл  = JavaScript

Revision as of 15:26, 11 March 2023

Ref­er­ences

Da­ta file of the ex­am­ples

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 Ob­jects by a Prop­er­ty (Price)

import products from "./data.mjs";

function sortProducts(data: { product: string, type: 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 sumPrices(data: { product: string, type: string, price: number }[]) {
    return parseFloat(
        data.reduce((acc, { price }) => acc + price, 0)
    ).toFixed(2);
}

Re­duce the prices of cer­tain prod­uct type in­to 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);
}

Fil­ter the Ob­jects by a Prop­er­ty and Map a new Ar­ray

import products from "./data.mjs";

function sumPrices(data: { product: string, type: string, price: number }[]) {
    return data
            .filter(({ type }) => type === "savory")
            .map(({ item, price }) => ({ item, price }));
}