JS Snippets: Array of Objects: Difference between revisions
m (Стадий: 4 [Фаза:Авторизиране, Статус:Разработен]; Категория:JavaScript) |
|||
(15 intermediate revisions by the same user not shown) | |||
Line 3: | Line 3: | ||
== References == | == References == | ||
*[https://github.com/metalevel-tech/exc-js-homework | *Scrimba: [https://scrimba.com/learn/interviewchallenges JavaScript Interview Challenges] | ||
*MLT GitHub: [https://github.com/metalevel-tech/exc-js-homework JavaScript Homework Tasks] | |||
== | == Example data files == | ||
{{collapse/begin}} | |||
<syntaxhighlight lang="shell" class="code-continue"> | <syntaxhighlight lang="shell" class="code-continue"> | ||
data.mjs | product-data.mjs | ||
</syntaxhighlight><syntaxhighlight lang="javascript"> | </syntaxhighlight> | ||
{{collapse/div}} | |||
<syntaxhighlight lang="javascript" line="1" class="mlw-collapsed-first-element"> | |||
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 lang="shell" class="code-continue"> | </syntaxhighlight> | ||
sort. | {{collapse/end}} | ||
{{collapse/begin}} | |||
<syntaxhighlight lang="shell" class="code-continue"> | |||
podcast-data.mjs | |||
</syntaxhighlight> | |||
{{collapse/div}} | |||
<syntaxhighlight lang="javascript" line="1" class="mlw-collapsed-first-element"> | |||
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"], | |||
} | |||
]; | |||
</syntaxhighlight> | |||
{{collapse/end}} | |||
{{collapse/begin}} | |||
<syntaxhighlight lang="shell" class="code-continue"> | |||
airlines-podcast-data.mjs | |||
</syntaxhighlight> | |||
{{collapse/div|#Output}} | |||
<syntaxhighlight lang="javascript" line="1" class="mlw-collapsed-first-element"> | |||
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 | |||
}, | |||
]; | |||
</syntaxhighlight> | |||
{{collapse/end}} | |||
== Sort Objects by a Property (Price)== | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
import products from "./product-data.mjs"; | |||
function sortProducts(data: { product: string, type: string, price: number }[]) { | |||
return data.sort((a, b) => a.price - b.price); | |||
} | |||
</syntaxhighlight> | |||
==Reduce the prices into a Sum== | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
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); | |||
} | |||
</syntaxhighlight> | |||
== Reduce the prices of certain product type into a Sum== | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
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); | |||
} | |||
</syntaxhighlight> | |||
==Filter the Objects by a Property and Map a new Array== | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
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 })); | |||
} | |||
</syntaxhighlight> | |||
==Get unique Tags from Podcast-data== | |||
<syntaxhighlight lang="typescript" line="1"> | |||
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; | |||
} | |||
</syntaxhighlight><syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
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; | |||
}); | |||
} | |||
</syntaxhighlight> | |||
== Back Recursive Search by .find() == | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
useEffect(() => { | |||
const isCostsArise = !!courses | |||
?.find(courseKey => allCourses | |||
?.find((courseObj: any) => | |||
courseObj.key === courseKey && courseObj.institution_id === 1 | |||
) | |||
); | |||
setCostsArise(isCostsArise); | |||
}, [courses]); | |||
</syntaxhighlight><syntaxhighlight lang="typescript" class="code-continue"> | |||
// Structure of the data: {}[] | |||
const data = [{ | |||
key: course.id, | |||
text: course.name, | |||
value: course.id, | |||
image: {avatar: true, src: ...}, | |||
institution_id: 0 | |||
}, | |||
key: course.id, | |||
text: course.name, | |||
value: course.id, | |||
image: {avatar: true, src: ...}, | |||
institution_id: 1 | |||
}, | |||
{ ... } | |||
]; | |||
</syntaxhighlight> | |||
==Order Movies Length According to a Flight Length== | |||
'''''The task. See the [[JS Snippets: Array of Objects#Example data files|Example data]] above.''''' | |||
''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: Just order according by the flight duration of 60 mins.''''' | |||
<syntaxhighlight lang="typescript" class="code-continue" line="1"> | |||
import products from "./airlines-podcast-data.mjs"; | |||
function sortByDuration(data, flightLength) { | |||
const lengthBase = 60; | |||
return data | |||
.sort((a, b) => { | |||
if (flightLength > lengthBase) 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`); | |||
}); | |||
} | |||
</syntaxhighlight><syntaxhighlight lang="typescript" class="code-continue"> | </syntaxhighlight><syntaxhighlight lang="typescript" class="code-continue"> | ||
sortByDuration(podcasts, 60); | |||
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue"> | |||
1. Something about Witches, 35 minutes | |||
2. Scrimba Podcast, 50 minutes | |||
3. Coding Corner, 55 minutes | |||
4. Crime Crime Crime, 70 minutes | |||
5. Mythical Creatures, 99 minutes | |||
6. Crime Fan, 150 minutes | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
sortByDuration(podcasts, 120); | |||
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue"> | |||
1. Crime Fan, 150 minutes | |||
2. Mythical Creatures, 99 minutes | |||
3. Crime Crime Crime, 70 minutes | |||
4. Coding Corner, 55 minutes | |||
5. Scrimba Podcast, 50 minutes | |||
6. Something about Witches, 35 minutes | |||
</syntaxhighlight> | |||
'''''Solution 2: Filter by the flight duration then order.''''' | |||
function | <syntaxhighlight lang="typescript" class="code-continue" line="1"> | ||
return data.sort((a | import products from "./airlines-podcast-data.mjs"; | ||
function filterByDuration(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... | |||
} | } | ||
</syntaxhighlight><noinclude> | </syntaxhighlight> | ||
<div id= | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
filterByDuration(podcasts, 60); | |||
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue"> | |||
1. Coding Corner, 55 minutes | |||
2. Scrimba Podcast, 50 minutes | |||
3. Something about Witches, 35 minutes | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="typescript" class="code-continue"> | |||
filterByDuration(podcasts, 120); | |||
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue"> | |||
1. Mythical Creatures, 99 minutes | |||
2. Crime Crime Crime, 70 minutes | |||
3. Coding Corner, 55 minutes | |||
4. Scrimba Podcast, 50 minutes | |||
5. Something about Witches, 35 minutes | |||
</syntaxhighlight> | |||
<noinclude><div id="devStage"> | |||
{{devStage | {{devStage | ||
| Прндл = JavaScript | | Прндл = JavaScript | ||
| Стадий = | | Стадий = 6 | ||
| Фаза = | | Фаза = Утвърждаване | ||
| Статус = | | Статус = Утвърден | ||
| ИдтПт = Spas | | ИдтПт = Spas | ||
| РзбПт = Spas | | РзбПт = Spas | ||
| АвтПт = {{REVISIONUSER}} | | АвтПт = Spas | ||
| УтвПт = {{REVISIONUSER}} | |||
| ИдтДт = 11.03.2023 | | ИдтДт = 11.03.2023 | ||
| РзбДт = 11.03.2023 | | РзбДт = 11.03.2023 | ||
| АвтДт = {{Today}} | | АвтДт = 11.03.2023 | ||
| УтвДт = {{Today}} | |||
| ИдтРв = [[Special:Permalink/32394|32394]] | | ИдтРв = [[Special:Permalink/32394|32394]] | ||
| РзбРв = [[Special:Permalink/32396|32396]] | | РзбРв = [[Special:Permalink/32396|32396]] | ||
| АвтРв = {{REVISIONID}} | | АвтРв = [[Special:Permalink/32398|32398]] | ||
| УтвРв = {{REVISIONID}} | |||
}} | }} | ||
</div> | </div> | ||
</noinclude> | </noinclude> |
Latest revision as of 15:17, 14 March 2023
References
- Scrimba: JavaScript Interview Challenges
- MLT GitHub: JavaScript Homework Tasks
Example data 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 Objects by a Property (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);
}
Reduce the prices into 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);
}
Reduce the prices of certain product type into 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);
}
Filter the Objects by a Property and Map a new Array
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 Podcast-data
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;
});
}
Back Recursive Search by .find()
useEffect(() => {
const isCostsArise = !!courses
?.find(courseKey => allCourses
?.find((courseObj: any) =>
courseObj.key === courseKey && courseObj.institution_id === 1
)
);
setCostsArise(isCostsArise);
}, [courses]);
// Structure of the data: {}[]
const data = [{
key: course.id,
text: course.name,
value: course.id,
image: {avatar: true, src: ...},
institution_id: 0
},
key: course.id,
text: course.name,
value: course.id,
image: {avatar: true, src: ...},
institution_id: 1
},
{ ... }
];
Order Movies Length According to a Flight Length
The task. See the Example data above.
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: Just order according by the flight duration of 60 mins.
import products from "./airlines-podcast-data.mjs";
function sortByDuration(data, flightLength) {
const lengthBase = 60;
return data
.sort((a, b) => {
if (flightLength > lengthBase) 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`);
});
}
sortByDuration(podcasts, 60);
1. Something about Witches, 35 minutes
2. Scrimba Podcast, 50 minutes
3. Coding Corner, 55 minutes
4. Crime Crime Crime, 70 minutes
5. Mythical Creatures, 99 minutes
6. Crime Fan, 150 minutes
sortByDuration(podcasts, 120);
1. Crime Fan, 150 minutes
2. Mythical Creatures, 99 minutes
3. Crime Crime Crime, 70 minutes
4. Coding Corner, 55 minutes
5. Scrimba Podcast, 50 minutes
6. Something about Witches, 35 minutes
Solution 2: Filter by the flight duration then order.
import products from "./airlines-podcast-data.mjs";
function filterByDuration(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...
}
filterByDuration(podcasts, 60);
1. Coding Corner, 55 minutes
2. Scrimba Podcast, 50 minutes
3. Something about Witches, 35 minutes
filterByDuration(podcasts, 120);
1. Mythical Creatures, 99 minutes
2. Crime Crime Crime, 70 minutes
3. Coding Corner, 55 minutes
4. Scrimba Podcast, 50 minutes
5. Something about Witches, 35 minutes