Below you can find the exercises for an array method training. Feel free to use your favourite online or desktop text editor. You may also use the console for these tasks as the arrays are pre-defined in this script. If you are ready with your task and would like to compare with my solution or if you feel stucked push the "Hint" button to find the solution.
Make a function that creates a range from x to y with Array.from()
Code:
const newArray = Array.from({ length: 10 }, function (item, index) {
return index;
});
Returns:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Check if the last array you created is really an array with Array.isArray()
Code:
const isArray = Array.isArray(newArray);
Returns:
true
Take the meats object and make three arrays with Object.entries(), Object.keys, Object.values()
Extra task:
Loop over the object entries and display meat and quantity.
Code:
const myEntries = Object.entries(meats);
const myKeys = Object.keys(meats);
const myValues = Object.values(meats);
Returns:
myEntries:
(3) [Array(2), Array(2), Array(2)]
0: (2) ['beyond', 10]
1: (2) ['beef', 5]
2: (2) ['pork', 7]
length: 3
[[Prototype]]: Array(0)
myKeys:
(3) ['beyond', 'beef', 'pork']
myValues:
(3) [10, 5, 7]
Extra task:
Object.entries(meats).forEach((meat) => {
const meatType = meat[0];
const qty = meat[1]
console.log(meatType, qty)});
Destructuring variables:
Object.entries(meats).forEach((meat) => {
const [meatType, qty] = meat;
console.log(meatType, qty)});
Destructuring the parameters:
Object.entries(meats).forEach(([meatType, qty]) => {console.log(meatType, qty)});
Display all bun types with " or " - use join()
Code:
const bunsJoin = buns.join(', ');
Returns:
'egg, wonder, brioche'
We have a string "hot dogs,hamburgers,sausages,corn" - use split() to turn it into a string
Code:
const stringSplit = 'hot dogs,hamburgers,sausages,corn'.split(',');
Returns:
(4) ['hot dogs', 'hamburgers', 'sausages', 'corn']
Take the last item off toppings with pop().
Add it back with push().
Take the first item off toppings with shift().
Add it back in with unshift().
Code:
const lastTopping = toppings.pop();
toppings.push(lastTopping);
const firstTopping = toppings.shift();
toppings.unshift(firstTopping);
Returns:
lastTopping: 'Cheese'
toppings: (10) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon', 'Pickles',
'Onions']
toppings.push(lastTopping);
toppings: (11) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon', 'Pickles',
'Onions', 'Cheese']
firstTopping: 'Mushrooms '
toppings.unshift(firstTopping)
toppings: (11) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon', 'Pickles',
'Onions', 'Cheese']
Apply pop(), push(), shift(), unshift() for toppings array, now immutable. Use spreads and new variables.
Code:
const toppingsCopy = [...toppings];
const topCopyLast = toppingsCopy.pop();
toppingsCopy.push(topCopyLast);
const topCopyFirst = toppingsCopy.shift();
toppingsCopy.unshift(topCopyFirst);
Returns:
toppingsCopy: (11) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon',
'Pickles', 'Onions', 'Cheese']
topCopyLast: 'Cheese'
toppingsCopy.push(topCopyLast)
topCopyFirst: 'Mushrooms'
toppingsCopy.unshift(topCopyFirst): (11) ['Mushrooms ', 'Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce',
'Avocado', 'Chiles', 'Bacon', 'Pickles', 'Onions', 'Cheese']
Make a copy of the toppings array with slice().
Make a copy of the toppings array with a spread.
Code:
const newToppings = toppings.slice();
const newToppings2 = [...toppings];
Returns:
newToppings: (11) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon',
'Pickles', 'Onions', 'Cheese']
newToppings2: (11) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon',
'Pickles', 'Onions', 'Cheese']
Take out items 3 to 5 of your new toppings array with splice()
Code:
newToppings.splice(3,3);
Returns:
(3) ['Chili', 'Lettuce', 'Avocado']
Find the index of Avocado within toppings with indexOf() / lastIndexOf().
Code:
toppings.indexOf('Avocado');
Returns:
5
Check if Mayonnaise is in the toppings with includes().
Add it if it's not.
Code:
const mayonnaiseIncluded = toppings.includes('Mayonnaise');
if(!mayonnaiseIncluded) {toppings.push('Mayonnaise')};
Returns:
false
(12) ['Mushrooms ', 'Tomatoes', 'Eggs', 'Chili', 'Lettuce', 'Avocado', 'Chiles', 'Bacon', 'Pickles', 'Onions',
'Cheese', 'Mayonnaise']
Flip those toppings around with reverse()
Code:
const reversedToppings = [...toppings].reverse();
Returns:
(11) ['Cheese', 'Onions', 'Pickles', 'Bacon', 'Chiles', 'Avocado', 'Lettuce', 'Chili', 'Eggs', 'Tomatoes',
'Mushrooms ']
Take the feedback array. Find the first rating that talks about a burger with find().
Extra task:
Turn your code into an arrow function with implicit return.
Create a re-usable callback function.
Code:
const findBurg = feedback.find(rating => rating.comment.includes('burg'));
Returns:
{comment: 'Love the burgs', rating: 4}
Turn your code into an arrow function with implicit return:
const findBurgRating = feedback.find((feedb) => feedb.comment.includes('burg'));
Create a re-usable callback function:
function findByWord(word) {
// since the callback does not take in more than 3 parameters, we parameter the search term here
return function (singleFeedback) {
// the higher order function iterates through all instances of the range, we parameter each instances as 'singleFeedback'
return singleFeedback.comment.includes(word); // this represents the object structure, here, we are looking for a rating which includes a specific value
};
}
const burgRating = feedback.find(findByWord('burg'));
Find all ratings in the feedback array that are above 2 with filter().
Extra task:
Create a re-usable callback function.
Code:
const goodReviews = feedback.filter((review) => review.rating > 2);
console.table(goodReviews);
Returns:
0 'Love the burgs' 4
1 'Smoothies are great, liked the burger too' 5
2 'Ambiance needs work' 3
Extra task:
Create a re-usable callback function.
function filterByMinValue(minValue) {
return function (review) {
return review.rating > minValue;
};
}
const goodReviews = feedback.filter(filterByMinValue(2));
console.table(goodReviews);
Find all ratings that talk about a burger with filter().
Extra task:
Utilize the reusable function you created in the find() exercise.
Code:
const allBurgRatings = feedback.filter((singleFeedback) => singleFeedback.comment.includes('burg'));
console.table(allBurgRatings);
Returns:
0 'Love the burgs' 4
1 'Smoothies are great, liked the burger too' 5
Extra task:
Utilize the reusable function you created in the find() exercise.
const allBurgRatings = feedback.filter(findByWord('burg'));
Remove the one star rating however you like!
Code:
const legitComment = feedback.filter((feedb) => feedb.rating !== 1);
Returns:
(4) [{…}, {…}, {…}, {…}]
0: {comment: 'Love the burgs', rating: 4}
1: {comment: 'Horrible Service', rating: 2}
2: {comment: 'Smoothies are great, liked the burger too', rating: 5}
3: {comment: 'Ambiance needs work', rating: 3}
Check if there is at least 5 of one type of meat with some().
Code:
Object.values(meats).some((value) => value > 5);
Returns:
true
Make sure we have at least 3 of every meat with every().
Code:
Object.values(meats).every((value) => value > 3)
Returns:
true
Sort the toppings alphabetically with sort().
Code:
toppings.sort();
Returns:
(11) ['Avocado', 'Bacon', 'Cheese', 'Chiles', 'Chili', 'Eggs', 'Lettuce', 'Mushrooms ', 'Onions', 'Pickles',
'Tomatoes']
Sort the order totals from most expensive to least with .sort().
Code:
orderTotals.sort((a, b) => {
return b - a;
})
Returns:
(8) [2222, 1644, 1002, 854, 634, 523, 342, 34]
Sort the prices object with sort().
Extra task:
Turn it back into an object.
Code:
const pricesSorted = Object.entries(prices).sort((a, b) => {
const valueA = a[1];
const valueB = b[1];
return valueA - valueB;
});
console.table(pricesSorted);
Returns:
(4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ['corn', 234]
1: (2) ['hotDog', 453]
2: (2) ['sausage', 634]
3: (2) ['burger', 765]
Extra task:
Turn it back into an object.
Object.fromEntries(pricesSorted);
Copy the below arrays to fulfil the exercises. If you use the console, don't need to copy them as they are included in the script.
const toppings = [
'Mushrooms ',
'Tomatoes',
'Eggs',
'Chili',
'Lettuce',
'Avocado',
'Chiles',
'Bacon',
'Pickles',
'Onions',
'Cheese',
];
const buns = ['egg', 'wonder', 'brioche'];
const meats = {
beyond: 10,
beef: 5,
pork: 7,
};
const prices = {
hotDog: 453,
burger: 765,
sausage: 634,
corn: 234,
};
const orderTotals = [342, 1002, 523, 34, 634, 854, 1644, 2222];
const feedback = [
{comment: 'Love the burgs', rating: 4 },
{comment: 'Horrible Service', rating: 2 },
{comment: 'Smoothies are great, liked the burger too', rating: 5 },
{comment: 'Ambiance needs work', rating: 3 },
{comment: 'I DONT LIKE BURGERS', rating: 1 },
];