JS Snippets: Array of Objects: Difference between revisions

From WikiMLT
Line 7: Line 7:


== Example data files ==
== Example data files ==
{{collapse/begin}}
<syntaxhighlight lang="shell" class="code-continue">
<syntaxhighlight lang="shell" class="code-continue">
product-data.mjs
product-data.mjs
</syntaxhighlight><syntaxhighlight lang="javascript">
</syntaxhighlight>
{{collapse/div}}
<syntaxhighlight lang="javascript" class="mlw-collapsed-first-element mlw-bind-collapsed-up">
export default [
export default [
     { product: "#1", type: "sweet",  price: 7.54 },
     { product: "#1", type: "sweet",  price: 7.54 },
Line 15: Line 18:
     { product: "#3", type: "savory", price: 3.79 }
     { product: "#3", type: "savory", price: 3.79 }
];
];
</syntaxhighlight><syntaxhighlight lang="shell" class="code-continue">
</syntaxhighlight>
{{collapse/end}}
{{collapse/begin}}
<syntaxhighlight lang="shell" class="code-continue">
podcast-data.mjs
podcast-data.mjs
</syntaxhighlight><syntaxhighlight lang="javascript">
</syntaxhighlight>
{{collapse/div}}
<syntaxhighlight lang="javascript" class="mlw-collapsed-first-element mlw-bind-collapsed-up">
 
export default [
export default [
     {
     {
Line 38: Line 47:
     }
     }
];
];
</syntaxhighlight><syntaxhighlight lang="shell" class="code-continue">
</syntaxhighlight>
{{collapse/end}}
{{collapse/begin}}
<syntaxhighlight lang="shell" class="code-continue">
airlines-podcast-data.mjs
airlines-podcast-data.mjs
</syntaxhighlight><syntaxhighlight lang="javascript">
</syntaxhighlight>
{{collapse/div}}
<syntaxhighlight lang="javascript" class="mlw-collapsed-first-element mlw-bind-collapsed-up">
 
export default [
export default [
     {
     {
Line 100: Line 115:
     },
     },
];
];
</syntaxhighlight>
</syntaxhighlight>
 
{{collapse/end}}
== Sort Objects by a Property (Price) ==
== Sort Objects by a Property (Price) ==
<syntaxhighlight lang="typescript" class="code-continue">
<syntaxhighlight lang="typescript" class="code-continue">
Line 184: Line 198:
         });
         });
}
}
</syntaxhighlight><noinclude><div id='devStage'>
</syntaxhighlight>
 
== Order Movies Length According to a Flight Length ==
'''The task.'''
 
''Welcome Aboard Scrimba Airlines. Our Scrimba Airlines in-flight entertainment package includes a variety of podcasts. We need to add a feature that suggests podcasts to our patrons based on whether a flight is short or long.''
 
''Your sort function should take two arguments: the podcast data and flight length. If the flight is 60 minutes or less, sort the podcast list from shortest to longest. If it's anything else, sort from longest to shortest.''
''Your function shouldn't return anything. Instead log a numbered list of the title and duration of each podcast to the console, like this:''
# ''Crime Fan, 150 minutes''
# ''Mythical Creatures, 99 minutes''
# ''Crime Crime Crime, 70 minutes''
# ''Coding Corner, 55 minutes''
# ''Scrimba Podcast, 50 minutes''
# ''Something about Witches, 35 minutes''
 
'''Solution 1: Filter by the flight duration.'''
 
<syntaxhighlight lang="typescript" class="code-continue">
import products from "./airlines-podcast-data.mjs";
 
function sortByDuration(data, flightLength) {
    return data
        .filter(({ duration }) => duration <= flightLength)
        .sort((b, a) => a.duration - b.duration)
        .map(({ title, duration }, i) => ({ i, title, duration }))
        .forEach(({ i, title, duration }) => {
            console.log(`${i + 1}. ${title}, ${duration} minutes`);
        });
        // Remove .forEach() to return the actual Object...
}
 
sortByDuration(podcasts, 60);
</syntaxhighlight>
 
'''Solution 2: Just order according by the flight duration.'''
 
<syntaxhighlight lang="typescript" class="code-continue">
import products from "./airlines-podcast-data.mjs";
 
function sortByDuration(data, flightLength) {
    return data
        .sort((a, b) => {
            if (flightLength > 60) return b.duration - a.duration;
            return a.duration - b.duration;
        })
        .map(({ title, duration }, i) => ({ i, title, duration }))
        .forEach(({ i, title, duration }) => {
            console.log(`${i + 1}. ${title}, ${duration} minutes`);
        });
        // Remove .forEach() to return the actual Object...
}
 
sortByDuration(podcasts, 60);
</syntaxhighlight>
<noinclude><div id='devStage'>
{{devStage  
{{devStage  
  | Прндл  = JavaScript
  | Прндл  = JavaScript

Revision as of 16:12, 11 March 2023

Ref­er­ences

Ex­am­ple da­ta files

product-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 }
];
podcast-data.mjs
export default [
    {
        id: 1,
        title: "Stranger Scrims",
        duration: 40,
        tags: ["supernatural", "horror", "drama"],
    },
    {
        id: 2,
        title: "The Scrim of the Dragon",
        duration: 60,
        tags: ["drama", "fantasy"],
    },
    {
        id: 3,
        title: "Scrim Hunters",
        duration: 22,
        tags: ["reality", "home improvement"],
    }
];
airlines-podcast-data.mjs
export default [
    {
        id: 1,
        title: "Scrimba Podcast",
        duration: 50,
        tags: ["education", "jobs", "technology"],
        hosts: ["Alex Booker"],
        rating: 10,
        genre: "education",
        paid: false
    },
    {
        id: 2,
        title: "Crime Fan",
        duration: 150,
        tags: ["crime", "entertainment", "mature"],
        hosts: ["Bob Smith", "Camilla Lambert"],
        genre: "true crime",
        rating: 5,
        paid: true
    },
    {
        id: 3,
        title: "Mythical Creatures",
        duration: 99,
        tags: ["entertainment", "general", "unicorns"],
        hosts: ["Esmerelda Shelley", "Duke Dukington", "Felix the Cat"],
        genre: "fantasy",
        rating: 8,
        paid: true
    },
    {
        title: "Crime Crime Crime",
        duration: 70,
        tags: ["crime", "entertainment", "mature"],
        hosts: ["Jessica Jones", "Humphrey Bogart", "Inspector Gadget"],
        genre: "true crime",
        rating: 6,
        paid: true
    },
    {
        title: "Something about Witches",
        duration: 35,
        tags: ["fantasy", "entertainment"],
        hosts: ["Frewin Wyrm", "Evanora Highmore"],
        genre: "fantasy",
        rating: 8,
        paid: false
    },
    {
        title: "Coding Corner",
        duration: 55,
        tags: ["education", "jobs", "technology"],
        hosts: ["Treasure Porth", "Guil Hernandez", "Tom Chant"],
        genre: "education",
        rating: 9,
        paid: false
    },
];

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

import products from "./product-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 "./product-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 "./product-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 "./product-data.mjs";

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

Get unique Tags from Pod­cast-da­ta

import products from "./podcast-data.mjs";

function getUniqueTagsForInLoop(data) {
    const unqTagsTrack = {};
    const unqTagsList = [];

    data
        .map(({ tags }) => tags)
        .flat().forEach(tag => {
            unqTagsTrack[tag] = true;
        });

    for (const key in unqTagsTrack) {
        unqTagsList.push(key);
    }

    return unqTagsList;
}
import products from "./podcast-data.mjs";

function getUniqueTagsWithFilter(data) {
    const unqTagsTrack = {};

    return data
        .map(({ tags }) => tags)
        .flat()
        .filter(tag => {
            if (!unqTagsTrack[tag]) {
                unqTagsTrack[tag] = true;
                return true;
            }
            return false;
        });
}

Or­der Movies Length Ac­cord­ing to a Flight Length

The task.

Wel­come Aboard Scrim­ba Air­lines. Our Scrim­ba Air­lines in-flight en­ter­tain­ment pack­age in­cludes a va­ri­ety of pod­casts. We need to add a fea­ture that sug­gests pod­casts to our pa­trons based on whether a flight is short or long.

Your sort func­tion should take two ar­gu­ments: the pod­cast da­ta and flight length. If the flight is 60 min­utes or less, sort the pod­cast list from short­est to longest. If it's any­thing else, sort from longest to short­est. Your func­tion shouldn't re­turn any­thing. In­stead log a num­bered list of the ti­tle and du­ra­tion of each pod­cast to the con­sole, like this:

  1. Crime Fan, 150 min­utes
  2. Myth­i­cal Crea­tures, 99 min­utes
  3. Crime Crime Crime, 70 min­utes
  4. Cod­ing Cor­ner, 55 min­utes
  5. Scrim­ba Pod­cast, 50 min­utes
  6. Some­thing about Witch­es, 35 min­utes

So­lu­tion 1: Fil­ter by the flight du­ra­tion.

import products from "./airlines-podcast-data.mjs";

function sortByDuration(data, flightLength) {
    return data
        .filter(({ duration }) => duration <= flightLength)
        .sort((b, a) => a.duration - b.duration)
        .map(({ title, duration }, i) => ({ i, title, duration }))
        .forEach(({ i, title, duration }) => {
            console.log(`${i + 1}. ${title}, ${duration} minutes`);
        });
        // Remove .forEach() to return the actual Object...
}

sortByDuration(podcasts, 60);

So­lu­tion 2: Just or­der ac­cord­ing by the flight du­ra­tion.

import products from "./airlines-podcast-data.mjs";

function sortByDuration(data, flightLength) {
    return data
        .sort((a, b) => {
            if (flightLength > 60) return b.duration - a.duration;
            return a.duration - b.duration;
        })
        .map(({ title, duration }, i) => ({ i, title, duration }))
        .forEach(({ i, title, duration }) => {
            console.log(`${i + 1}. ${title}, ${duration} minutes`);
        });
        // Remove .forEach() to return the actual Object...
}

sortByDuration(podcasts, 60);