Finding a Good Deal explainer

The aim of this puzzle: Use the .forEach() method to find the mininum value of the flightPrices array.

Walkthrough of the solution: The max and min variables start out storing the 1st number in the array. These need to be updated to the largest and smallest values in the array. This can be done using the compareToMaximum and compareToMinimum functions. The compareToMaximum function takes a value and checks if it’s larger than the current max value. If it is, then max gets updated to that new value, otherwise it stays the same. compareToMinimum does a similar thing but checking if the value is smaller than the current min. All that needs to happen is run all the values of the array through the 2 functions.

Instead of a For Loop, the .forEach() method can be used. When .forEach() is applied to an array, each element of the array is passed into the callback function given to .forEach(). If you use flightPrices.forEach(compareToMinimum), then each of the elements of the flightPrices array will be used as the input for compareToMinimum(). That compareToMinimum() function will update the value of the min variable.

Sample code solution:
(Tap below to reveal)

import { flightPrices } from 'grasshopper.travel';

let max = flightPrices[0];
let min = flightPrices[0];

function compareToMaximum(value) {
  max = value > max ? value : max;
}

function compareToMinimum(value) {
  min = value < min ? value : min;
}

console.log(flightPrices);

flightPrices.forEach(compareToMaximum);
console.log('Maximum: ' + max);

flightPrices.forEach(compareToMinimum);
console.log('Minimum: ' + min);

JavaScript Concepts: Callback Functions, Calling Functions, Code Block (function), console.log(), Conditionals (ternary statement), .forEach(), import
Additional Code (hidden code that runs before the puzzle’s code):

let flightPrices= [...Array(6)].map(i => pickRandom(275)+125);
flightPrices.splice(pickRandom(6),0,Math.min(...flightPrices)-pickRandom(25));
1 Like

This app makes me something like
‘I understand Spanish but cannot speak’

4 Likes

.forEach() is similar to a for...of loop.

flightPrices.forEach(compareToMaximum);

is the same as

for (let element of flightPrices) {
  compareToMaximum(element);
}

If you just want to run each value in an array through a function, .forEach() is a way you can do it with a little less code.

–Frankie

4 Likes

The part I don’t understand is how the test exactly works for the comparisons. I get the premise but not how the code plays out, specifically the equals after the max or min at the beginning of the operation, that only “value” follows “?” as the Then outcome for a true “If” test, and then how “min” by itself as the false test outcome means anything. Does anything. I get THAT it keeps the value of min as min going forward instead of changing to the value just compared with it. I just don’t get how so or why the coding language is so minimal there. Probably for efficiency but I’m trying to retain this and I’m finding it a bit more difficult because of that.

Thank you. I hope that all makes sense. Please ask for clarification if not.

1 Like

Hey there, great question!

Ternaries are popular because they can do in 1 line of code what an if…else statement can do in 5 or 6, which is a useful shortcut that can make the work of writing code a bit faster. The tradeoff is that ternaries can sometimes be a bit miserable to read.

Let’s take a look at one of the ternaries in this puzzle:

function compareToMaximum(value) {
  max = value > max ? value : max;
}

Let’s say that max is 5, and we call the function with 6 as an argument, like this:
compareToMaximum(6)

The ternary inside the function will check:

max = (is 6 > 5) ? 6 : 5;

Think of the max = at the beginning of the line as reaching a long arm over the test. If the test is true, the max = will grab the value after the ?. If the test is false, it will grab the value after the :

Hope this makes sense! Let me know if you have any further questions.

Ben

3 Likes

It does make sense. That answer will do for my current needed level of understanding.

Thanks :slightly_smiling_face:

2 Likes

what is the difference between .foreach () and .filter (), both of them seem to have the same way of working, looping to the aray and using the callback function

1 Like

Good question.

`.filter()’ is a way to apply a test to every element in an array and return the elements that pass into a new array.

For example, taking an array of mixed numbers and filtering the even numbers into their own array:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let evenNumbers = numbers.filter(num => num % 2 === 0);
// the % operator finds the remainder after division of one number by another

The .forEach() method runs a callback function with each element as an argument, but doesn’t return anything, so you wouldn’t use it to define a new variable like you would with .filter().

For example, you can use it to print every element in an array like this:

['alpha', 'beta', 'charlie'].forEach(word => console.log(word));

Hope that helps! Let me know if you have any more questions.
Ben

2 Likes

I am little confused with this line,

let max = flightprices[0];
let min = flightprices[0];

is it declaring max/min = 0; or picking 0th element from flightprices array. Need help.

1 Like

Hey there, both of the variables are initially set to the first element (at index 0) of the flightPrices array.

Later in the code, we use the compareToMinimum and compareToMaximum functions with .forEach to figure out what the actual min and max values are, but to start, we just set their values to the first element.

Hope this clarifies things! Let me know if you have any further questions.
Ben

3 Likes
var flightprices = ['200','278','470','420','1024']

var max = flightprices[0];

var min = flightprices[0];

function compareMaxv(value){

   max = value>max?value:max;

};

function compareMinv(value){

  min = value<min?value:min;

};

console.log(flightprices.join())

flightprices.forEach(compareMaxv)

flightprices.forEach(compareMinv)

console.log("Maximum:" + max)

console.log("Minimum:" + min)

Help:
o/p
[Running] node “c:\Users\Ganesh R\Desktop\ganesh\forEach.js”
200,278,470,420,1024
Maximum:470
Minimum:1024

what is the problem with code??
please anyone explain!!

Thanks,
th3 j35t3r

1 Like

Hey there, it looks like you’ve entered the numbers in the flightPrices array as strings of text, instead of numbers.

Using the < or > operator with strings means it will compare the strings as if it’s checking dictionary order. In fancy terms, this is called a “lexicographical comparison”.

For example: 'cat' is less than 'dog' because 'c' is less than 'd'. '1024' is less than '200' because the string '1' is less than the string '2'.

Change your array to store numbers, like this:

var flightPrices = [200, 278, 470, 420, 1024]

Hope this helps!
Ben

4 Likes

Hi,

How would you write this code without using the .foreach to loop through? Could you do it using both options (for var of flightprices) and (let i = 0; i < flightprices.length; i++)? If so could you please write the code?

Thank you.

Yeah, you could get the same output with different methods of iteration, whether you use a for loop, classic for loop, or Array.forEach(), like this:


// these all do the same thing:

// for of loop:
for (let flight of flightPrices) {
    compareToMaximum(flight);
}

// classic for loop:
for (let i = 0; i < flightPrices.length; i++) {
    compareToMaximum(flightPrices[i]);
)

// Array.forEach():
flightPrices.forEach(compareToMaximum)

Since Array.forEach() was added to JavaScript in 2015, it’s become very popular because of how easy it is for humans to read. Code readability makes it easier for teams of programmers to work together.

Hope this helps!
Ben

1 Like

what will be exact difference between the .filter function and .foreach function
Bcoz both functions give result based on what is declared in a function cal ???
do this both functions are same

what will be exact difference between the .filter function and .foreach function
Bcoz both functions give result based on what is declared in a function cal ???
do this both functions are same

Hello there
it seems the web version is not optimized as its hiding or truncating part of the console.log , leading to confusion.
you should remove the scroll bar and add a line break to the console.log(flightprice); result as I’ve spent some time trying to understand why the console.log min doesnt look like to return the smallest value or the array
see screenshot to compare android version VS desktop version

Thanks for confirming that.forEach() is similar to for… of loop. I was thinking what’s the difference between these two and why they exist if they do the same job.

Hi Pankaj,
This question was already asked and answered above. Here is the link of the same Finding a Good Deal explainer
I hope it helps.
Abdulla

1 Like

hey thanks for the suport…

1 Like