Chapter 4 - Exercises

Hi @JanjoHR1,

I’m going to post my feedback and answers to your questions for each exercise separately:

Sum of a Range

function range(start, end, step = start < end ? 1 : -1) {...}

There are 2 important concepts in this function header:

  1. Default parameter
  2. Ternary operator

If an argument is left undefined in a function call, this will result in one of the function’s parameters being undefined as well. We can handle this situation by setting a default parameter value in the function header as follows:

function range(start, end, step = 1) {...}

/*  If a value for step has been passed to the function, then:
    step will have that value */
/*  If step has been left undefined, then:
    it will be assigned a default value of 1  */

This is a ternary operator

start < end ? 1 : -1 

/*

?   performs the same function as  IF
2nd expression (1) is returned if 1st expression evaluates to TRUE
:  performs the same function as  ELSE
3rd expression (-1) is returned if 1st expression evaluates to FALSE

*/

It provides the same logic as an if...else statement. So in this exercise, it handles the two possible default step parameters (1 or -1) depending on whether our range is an ascending or descending one. However, it does this more concisely than an if...else statement, by providing this logic all within the actual function header. We can use an if....else statement but it would be less concise and look something like this:

function range (start, end, step = 1) {
   let newArr = [];
   if (step === 1 && start > end) step = -1;
   // etc.
}

or this…

function range (start, end, step) {
   let newArr = [];
   if (step === undefined) {
      if (start <= end) step = 1;
      else step = -1;
   }
   // etc.
}

You can find out more about the ternary operator in the MDN web docs :


The MDN web docs are a great resource in general, and I use them a lot for reference and research purposes.
1 Like

Hi again, @JanjoHR1!

Your posted solution is great :+1:
The key here is that the original array is not mutated i.e. it’s not changed. The reversed array is a new array. We can check this with two console.log statements:

// the one you have
console.log(reverseArray(days));
// => ["Sun", "Sat", ... etc. ... , "Tue", "Mon"]

// another to log the original array to check whether it's been reversed or not
console.log(days);
// => ["Mon", "Tue", ... etc. ... , "Sat", "Sun"]
// it hasn't changed

This is a great solution, but it isn’t one that reverses the array in place. It’s a great alternative to reversing the array (Part 1) i.e. not changing the original array, and returning a new array which is the reverse of the original. You can see that this is the case, by again running the 2 console.log statements that I outlined above:

// the one you have
console.log(reverseArrayInPlace(arr));   // => [5, 4, 3, 2, 1]

// another to log the original array to check whether it's been reversed or not
console.log(arr);                        // => [1, 2, 3, 4, 5]
// it HASN'T changed

The objective in Part 2 is to build a function that mutates the original array, so that, after running the function:

console.log(arr);                       // => [5, 4, 3, 2, 1]
// it HAS changed

Once you have understood this difference in the outcome we are trying to achieve, have a look at the hints in the course book (which you can display by clicking Display hints, in blue, below the exercise instructions) and have another go yourself. You may also need to take a quick peek at the model answer, or at other students’ solutions posted and reviewed here in the forum, just for a helping hand.

This last part is very difficult and a real challenge, and so if you started this course as a complete beginner, it’s perfectly normal, and to be expected, that you will need to look at the answer at some stage before being able to complete it yourself. Working backwards from the answer, analysing it, finding out how it does what it does, is also a great learning technique. After having done that, another good learning approach to use is to then try the exercise again from scratch without looking back at the answer (like a memory test). You can also try to do this after having left it for a certain period of time (say, the next day, then after a few days, then a week etc. etc.) This builds up longer-term retention.

You’re doing great! :slight_smile: … and making excellent progress! :muscle: … a lot more than it might seem like to you at times…

2 Likes

Hi @Bette,

Sum of a Range

Nice solution :ok_hand:

Your code handles the reverse step successfully and also a default incremental step… but we also need to handle a default negative (or reverse) step. At the moment your code only handles the reverse step if a step parameter with a minus value is defined. However, because your default step parameter is always step = 1 this won’t handle a function call of:

console.log(range(5, 2));   // undefined step parameter
// This enters an infinite loop and doesn't output [5, 4, 3, 2]

For your function to handle that, it needs to be able to change the default step value from 1 to -1, depending on whether the range is an ascending or descending one.

Reversing an Array (Part 1)
Your solution successfully returns a new array which is the reverse of the original one. The problem, however, is that the original array is now empty, because by using .pop() you have removed the numbers and placed them in the new array. Can you amend your code so that it still produces the same reversed new array, but also maintains the original array unchanged?

Reversing an Array (Part 2: in place)
You’ve nailed it! :muscle:

That’s perfectly fine to get some help (even to eventually look at the solution), as long as you first spend plenty of time doing battle with it yourself. Then, when you do look at the solution, you should spend a lot of time analysing it and getting to a point where you really understand what the different chunks of code are actually doing, and why they are efficient at doing what they do. It is clear from your comment, that you have done this :+1:

At the same time you should also keep in mind that there are always valid alternatives to the model answer.

Good luck with the modifications! :slight_smile:

Ohh sorry, I was thinking that we just need to reverse the same array withouth it being mutated.
For this one I have another solution.

// 1. Let's put up a constant function that will reverse an array in place, and we give her an array as parameter to reverse... now for the rest this is how I learned it... someone else could choose a different approach.
   const reverseArrayInPlace = (array) => {
// we pass in temp variable and then loop through an array (only half length, so.. devided by 2) 
       let temp
        for ( let i = 0; i < array.length /2; i++) {
/*here we are doing the actual flipping of the array.
we set temp to equal our first element in the array, then we match the first element with the last element, and we set it with - i to do the actual looping in the array. At the end we match the last element with the first. (reversing is finished).*/
         temp = array[i]
         array[i] = array[array.length - 1 - i]
         array[array.length - 1 - i] = temp
}
// and here we just return the reversed array
return array
}
const array = [1,2,3,4,5,6,7,8,9]
console.log(array) 
// [1,2,3,4,5,6,7,8,9]
console.log(reverseArrayInPlace(array))
// [9,8,7,6,5,4,3,2,1]
console.log(array)
// [9,8,7,6,5,4,3,2,1]

For the first assignment I will check out some videos and learn more about the ternary operator. But I really appreciate all of the detailed comments regarding the exercises. Thank you :slight_smile:

1 Like

You’re very welcome @dragos_andrei_87!

Great! The sum of the descending arrays is now calculating correctly each time for any step value :+1:

You can actually slim down the code for the sum calculation even more. There is no need to perform the if...else logic as the array has already been generated. So, you only need to call the function totalSum() once. Here is the code for just the sum calculation, with my suggested amendments (I’ve commented out the removed code) so you can see more clearly what I mean…

//Button Step Total
$('#SumDisplay2').click(function(){
   // var x = parseInt($('#argument1').val());
   // var y = parseInt($('#argument2').val());
   // var z = parseInt($('#argument3').val());
   var total = 0;

   function totalSum(){
      ArrayNumber.forEach(myFunction);
      function myFunction(item){
         total+=item;
      }
   };

   totalSum()    // added in place of the following conditional execution

   /*
   if(x<y){
      if(z==""){
         totalSum();
      }
      else{
         totalSum();
      }
   }
   else if(x>y){
      if(z==""){
         totalSum();
      }
      else{
         totalSum();
      }
   }
*/
   $('#argument1').val("");
   $('#argument2').val("");
   $('#argument3').val("");

   $('#StepTotal').text(total);
});

What do you think?

Also, having now seen how the fields clear automatically when Total is clicked, I think it would be better to have a separate Clear/Reset button for the user to decide when they want to do it. The automatic reset is annoying if you want to adjust your previous input, as you then have to remember everything and input it again. What do you think?

Anyway, it’s your program, so I’ll leave you to continue playing and experimenting with it :slightly_smiling_face:

1 Like

Hi @Matoshi,

I’m going to give you feedback for each exercise in separate posts.

Sum of a Range

You are nearly there with this :ok_hand:
You just need a few finshing touches:

  1. You need to place your arrayNumb and counter variables within their functions, rather than declare them outside. This doesn’t matter if the functions are only called once. However, if we want to repeat the computations, these variables need to be reset to empty/zero each time. Otherwise, the array will continue to grow with each range created, and the sum total will also keep getting bigger, and so acting as a cumulative total, rather than the total of each separate range generated.

  2. The range() function now needs to return arrayNumb

       return arrayNumb;
  1. The sum() function now needs to be called with an argument that in turn calls the range() function. This will effectively pass the value returned from range() (arrayNumb) to sum() so that the sum total of all the numbers in the range is calculated:
       sum(range(5, 2, -1 ));
  1. Both function calls need to be logged to the console, so that we can view the range and its sum total as outputs.
console.log(range(5, 2, -1));        // => [5, 4, 3, 2]
console.log(sum(range(5, 2, -1)));   // => 14

The only functionality asked for in the exercise that your program doesn’t attempt to handle is if the step parameter is not given. Can you adapt your code to include a step default parameter which incorporates conditional execution to default to either 1 or -1 depending on whether the range is ascending or descending?

You’re making great progress! :muscle:

My exercise results

I found this exercise really challenging especially reversing the array in place. I had to research quite a lot and even when I found a way to implement it it took a major effort to get my head around it. I did realize of coarse that splitting the array was part of the solution but it was a real challenge.

Here is my homework

Exercise 4 (Range/Sum Functions)

The whole doc is required because the display features depend on elements in the body…

<!DOCTYPE html>
<html>
  <head>
    <title>Range and Sum Function</title>
  </head>
  <script language="JavaScript">
  function writeToPage(data) {
          // Write some data to page
          if(!data) {
            document.getElementById('myId').innerHTML = "";
          } else {
            document.getElementById('myId').innerHTML += data;
          }
          return;
  }

  function textColor(color) {
    // adds a little color ot the output text
      return "<font color=\"" + color + "\">" + this + "</font>";
  }

  String.prototype.color = textColor; // create new string property for color

  function posToNegative(num) {
    // converts step in range to negative if start > end
    return -Math.abs(num);
  }


  function range(start, end, step) {
    //alert(start + end + step)
    // creates array while start is < end || start > end
    var myArray = new Array();
    if(start > end) {
      // build the array
      step = posToNegative(step); // if start > end  make step negative
       for(let i = start; i >= end; i += step) {
         myArray.push(i);
       }
    } else {
      for(let i = start; i <= end; i += step) {
        myArray.push(i);
      }
    }
    // Make the array text pretty to show to user
    var display = "<h2>Function Range</h2>The numbers ";
    for(let i = 0; i < myArray.length; i++) {
      display += myArray[i].toString().color('green');
      if(i < myArray.length -1) {
        display += ", ";
      }
    }
    writeToPage(display + " were written to " + "myArray".color('red'));
    // write result of range() to the page.
    return(myArray);
  }

  function sum(thisRange) {
    writeToPage("<h2>Function Sum</h2>The numbers ");
    var sum = 0;
    for(let i = 0; i <= thisRange.length -1; i++) {
      sum += thisRange[i];
      writeToPage(Number(thisRange[i]).toString().color('green'))
      if(i < thisRange.length -1) {
        writeToPage(" + ");
      } else {
        writeToPage(" = ");
      }
    }
    writeToPage(Number(sum).toString().color('green'));
    return;
  }


  function getInputValues() {
    // Gets input values from the user and retruns string
    return prompt("I need 3 values to pass to the range().\n These should be a coma separated list of values\n for example\n 1, 10, 2 which convert to start, end, step respectivly");
  }

  function doIt() {
    writeToPage("")
    userRangeValues = getInputValues();
    rangeValuesSplit = userRangeValues.split(",");
    sum(range(Number(rangeValuesSplit[0]), Number(rangeValuesSplit[1]), Number(rangeValuesSplit[2])));
    writeToPage("<br><br><button onClick='doIt()'>Try Another Calculation</button>")
    writeToPage("</div>")
    return;
  }
  </script>
  <body id="body" onLoad="doIt()">
    <div id="myId">
    </div>
  </body>
</html>

Exercise 4 (Reversing Arrays with Speed test)

The whole body is included because display depends on body element

Regarding the question of speed and which method is quicker??

Impossible to tell just by observation. All the research I have done researching this exercise leads me to believe there are too many variables at play to be truly certain. Calling properties of objects outside the local scope are suggested to be slower and less efficient. It is also suggested recursion is slower than looping.

For my exercise i used loops for both and the reverse function is using local declarations and objects and the inplace reverse is using global objects outside of the function scope. I couldn’t notice any observable difference in loops but when i attached the performance.now() object to both functions it turns out some of the suggestions from the internet on speed are incorrect and the function i expected to be faster which was using the local declared objects and declarations was much slower. In fact nearly 50% slower. I wonder if the same results are returned from a different computer.

<!DOCTYPE html>
<html>
  <head>
    <title>Reverse Array's with Speedtest</title>
    <script language="JavaScript">
    function writeToPage(data) {
      document.getElementById('myID').innerHTML += data;
    }



    function reverse(array) {
      let length = array.length - 1;
      localArray = new Array();
      for(let i = 0; i <= length; i++) {
        localArray.push(array[length - i]);
      }
      writeToPage("<h2>Out of Place Reverse</h2>Initial array set to " + array + "<br>reversed localArray set to " + localArray);
      return;
      }


      let inPlaceArray = [1,2,3,4,5,6,7,8,9,10];
      let length = inPlaceArray.length;
      let middle = length / 2;
      let temp = null;

      function reverseArrayInPlace() {
        writeToPage("<h2>In Place Reverse</h2>Initial array set to " + inPlaceArray)
        for(i = 0; i <= (length -1) / 2; i++) {
          //alert(i)
          temp = inPlaceArray[i];
          inPlaceArray[i] = inPlaceArray[length - 1 - i];
          inPlaceArray[length - 1 - i] = temp;

        }
        writeToPage("<br>reversed inPlaceArray = " + inPlaceArray);
      }


      function timeIt() {
        var t0 = performance.now();
        reverse([1,2,3,4,5,6,7,8,9,10]);
        var t1 = performance.now();
        writeToPage("<br>Duration of exeacution was " + (t1 - t0) + " ms");
        t2 = performance.now();
        reverseArrayInPlace();
        t3 = performance.now();
        writeToPage("<br>Duration of exeacution was " + (t3 - t2) + " ms");
        if(t1 - t0 > t3 - t2) {
          writeToPage("<h2>Results from the Speed Test</h2>")
          writeToPage("<br>Reversing an array in place is " + ((t1 - t0) - (t3 - t2)) + " ms quicker.")
        } else if(t3 - t2 > t1 - t0) {
          writeToPage("<br>Reversing an array out of place is " + ((t3 - t2) - (t1 - t0)) + " ms quicker.")
        } else {
          writeToPage("There was no difference in speed detected.")

        }
      }


    </script>
    </head>
    <body onLoad="timeIt()">
        <center>
        <div id="myID" style="width:50%; text-align:center;"></div>
        </center>
    </body>
</html>

One more additional extra to array reversing recursively

I got curious and decided to make one more addition to the script to account for recursion V’s looping in regard to speed and which is faster and the results were even more surprising to me. It was suggested in the eloquent javascript book that recursion was slower than looping. maybe I read it incorrectly but my final script shows that recursive reversing of in place array is the quickest.

<!DOCTYPE html>
<html>
  <head>
    <title>Reverse Array's with Speedtest Recursion V's Looping</title>
    <script language="JavaScript">
    function writeToPage(data) {
      // Any text passed will be written to document
      document.getElementById('myID').innerHTML += data;
    }

    function colorText(color) {
      // Colors any call to it using the color passed to it.
      return "<font color=\"" + color + "\">" + this + "</font>";
    }

    String.prototype.color = colorText; // Create an extra property using colorText()

    function reverse(array) {
      // Reverse the array out of place

      // define some local variables
      let length = array.length - 1;
      localArray = new Array();
      for(let i = 0; i <= length; i++) {
        localArray.push(array[length - i]);
      }
      // When loop is complete write result
      writeToPage("<h2>Out of Place Reverse</h2>Initial value of "
      + "array[]".color('green')
      + " set to "
      + array.toString().color('red')
      + "<br>The reversed value of "
      + "localArray[]".color('green') + " is "
      + localArray.toString().color('red'));
      return;
      }

      // Set some globals for reverse in place
      let inPlaceArray = [1,2,3,4,5,6,7,8,9,10];
      let length = inPlaceArray.length;
      let temp = null;

      function reverseArrayInPlace() {
        // Reverse the array in place
        writeToPage("<h2>In Place Reverse</h2>Initial value of "
        + "inPlaceArray[]".color('green')
        + " set to "
        + inPlaceArray.toString().color('red'));
        for(i = 0; i <= (length -1) / 2; i++) {
          temp = inPlaceArray[i];
          inPlaceArray[i] = inPlaceArray[length - 1 - i];
          inPlaceArray[length - 1 - i] = temp;

        }
        // When loop is complete write the result
        writeToPage("<br>The reversed value of "
        + "inPlaceArray[]".color('green')
        + "is "
        + inPlaceArray.toString().color('red'));
      }
      // Set some globals for the recursive function
      let inPlaceArray1 = [1,2,3,4,5,6,7,8,9,10];
      let length1 = inPlaceArray1.length;

      function reverseArrayInPlace1(cnt) {
        // Recursive function to reverse array in place
        if(cnt <= (length1 - 1) / 2) {
          temp = inPlaceArray1[cnt]; // Reuse previous temp variable
          inPlaceArray1[cnt] = inPlaceArray1[length1 - 1 - cnt];
          inPlaceArray1[length1 - 1 - cnt] = temp;
          return reverseArrayInPlace1(++cnt);
        } else {
          // When recursion complete write the result
          writeToPage("<br>The reversed value of "
          + "inPlaceArray1".color('green')
          + "is "
          + inPlaceArray1.toString().color('red'));
          return;
        }

      }


      function timeIt() {
        // To test which method is faster will use performance.now() to time
        // duration of of function..
        writeToPage("<h1>Reverse Array Looping/Recursive</h1>")
        var t0 = performance.now(); // Set start of timer for reverse()
        reverse([1,2,3,4,5,6,7,8,9,10]);
        var t1 = performance.now(); // End timer for reverse()
        writeToPage("<br>Duration of exeacution was "
        + (t1 - t0).toString().color('red')
         + " ms");

        t2 = performance.now(); // Start timer for reverseArrayInPlace()
        reverseArrayInPlace();
        t3 = performance.now(); // End timer for reverseArrayInPlace()
        writeToPage("<br>Duration of exeacution was "
        + (t3 - t2).toString().color('red')
        + " ms");

        writeToPage("<h2>Reverse Array in Place with recursion</h2>");
        writeToPage("Initial value of "
        + "inPlaceArray1[]".color('green')
        + "is "
        + inPlaceArray1.toString().color('red'));

        t4 = performance.now(); // Start timer for recursive reverseArrayInPlace1()
        reverseArrayInPlace1(0);
        t5 = performance.now(); // End timer for recursive reverseArrayInPlace1()
        writeToPage("<br>Duration of execution was "
        + (t5 - t4).toString().color('red')
        + " ms.");

        writeToPage("<h2>Results from the Speed Test</h2>");

        if(t1 - t0 > t3 - t2 && t5 - t4 > t3 - t2) {
          // All timers set now do some condition testing
          // Then perform the math to figure out which is faster
          // Then compare fastest to the 2 slowest reverses.
          writeToPage("<br>Reversing an array in place is <br>"
          + ((t1 - t0) - (t3 - t2)).toString().color('red')
          + " ms quicker than out of place and <br>"
          + ((t5 - t4)- (t3 - t2)).toString().color('red')
          + " ms quicker than recursion.");
        } else if(t3 - t2 > t1 - t0 && t5 - t4 > t1 - t0) {
          writeToPage("<br>Reversing an array out of place is <br>"
          + ((t3 - t2) - (t1 - t0)).toString().color('red')
          + " ms quicker than in place and <br>"
          + ((t5 - t4) - (t1 - t0)).toString().color('red')
          + " ms quicker than recursion.");
        } else if(t1 - t0 > t5 -t4 && t3 - t2 > t5 - t4 ){
          writeToPage("Reversing an array in place with Recursion is <br>"
          + ((t1 - t0) - (t5 - t4)).toString().color('red')
          + " ms quicker than out of place for loop and <br>"
          + ((t3 - t2) -(t5 - t4)).toString().color('red')
          + " ms quicker than in place for loop.");
        } else {
          writeToPage("<h2>Shocking Result</h2>Back to drawing board.");
        }

      }


    </script>
    </head>
    <body onLoad="timeIt()">
        <center>
        <div id="myID" style="width:50%; text-align:center;"></div>
        </center>
    </body>
</html>

P.S perhaps i jumped the gun too soon. earlier the recursive function was registering fastest 100% of the time and now while i have been doing some cosmetic surgery to my code it appears the out of place loop is coming in quickest now. Im not sure what is going on any more. Is it possible to have so much variability in the speeds of execution. Is it a side effect of performance.now(), anyway i tried to be 100% conclusive on speed and it seems not possible at the moment.

Hi again @Matoshi,

Reversing an Array (Part 1)

Exactly the same points that I mentioned about the previous exercise, also apply to Part 1 of this exercise. Your code in general is excellent. The issue is just with the finishing touches.

Here are my suggested amendments to your code for Part 1…

// 2. Reversing an array
    
var abas=[1,2,3,4,5];

function reversArray (array){
   var newArray=[];              // moved from outside to inside the function
   let i=1;
   while(i<=array.length){
      newArray.push(array[array.length-i]);
      i++;
   }
   return newArray;              // added
}  

console.log(reversArray(abas));  //console.log() added
// => [5, 4, 3, 2, 1]

console.log(abas);               // added to show original array unchanged
// => [1, 2, 3, 4, 5]

// newArray                      // removed

Reversing an Array (Part 2 — in place)
Your code is excellent. The only thing you need to add is a console.log() to the function call, in order to be able to view the output:

console.log(reverseArrayInPlace(abas)); 
// => [5, 4, 3, 2, 1]

And I would also log the original input array to the console in order to check that this is what has been changed within the function (i.e. in place):

console.log(abas);
// => [5, 4, 3, 2, 1]

Well done! You’ve made excellent progress with your approach to the course book exercises :muscle:

1 Like

This is great @JanjoHR1!

I can see from the comments you’ve added (really good detail by the way) that you have really understood the difference between the 2 types of reversing, and the mechanics of this “reverse-in-place” method.

It’s also good to see that you’ve understood what I meant about using different console.log() statements to check what is actually being changed/reversed :+1: I think doing that also really helps to get things clearer in your own mind about what’s going on.

By the way, you could make your function even more concise by declaring the temp variable in the for loop directly, when you first assign a value to it. That way you don’t need to declare it as an empty variable beforehand i.e.

/* let temp */          // remove this line

let temp = array[i]     // just add the keyword 'let' here
2 Likes

function range(start, end, step = start < end ? 1 : -1) {
let array = [ ];

if (step > 0) {
for (let i = start; i <= end; i += step) array.push(i);
} else {
for (let i = start; i >= end; i += step) array.push(i);
}
return array;
}

function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}

function reverseArray(array) {
let output = [ ];
for (let i = array.length - 1; i >= 0; i–) {
output.push(array[i]);
}
return output;
}

function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}

1 Like

Hello Jonathan,

Your comments are really helpful and made me understand everything better. My old code was really hard to read and follow. I have no idea why I haven’t chosen your way of solving the exercise. :slight_smile:
The button for resetting makes the function more user friendly.

Thank you again for your kind and generous support.

1 Like

Hey Dragos!

Don’t be too hard on yourself! It’s often harder to see these improvements when we’ve built the program ourselves from the start, because we get so wrapped up in the details. That’s why it’s always good to have someone else review your code with a fresh pair of eyes. And that’s why developers usually work as part of a team.

You’re doing great! And the fact that you’re so open to feedback, and ways to improve, will make you even greater! :smiley:

2 Likes

//REVERSING AN ARRAY
function reverseArray(array){
var newArray=[];

        for (var i = array.length - 1; i >= 0; i--) {
            newArray.push(array[i]);
    }
    return newArray;

}
console.log(reverseArray([“Apple”, “Orange”, “Banana”,“Pineapple”]));
//=(4) [“Pineapple”, “Banana”, “Orange”, “Apple”]

/* reverseArrayInPlace answer coppied from https://eloquentjavascript.net/code/#4.2
*Math.floor will round numbers downward to the nearest integer
what the function does is it will interchange 1st and last element,2nd and 2nd to
the last element so on and so forth, and maintain the midlle element.
*/
function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}

let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//=(5) [5, 4, 3, 2, 1]

1 Like

function range(start,end,count = start < end){
let array = [];

  if (count > 0) {
    for(let i = start; i <= end; i += count) array.push(i);
  }

else{
  for(let i = start; i >= end; i += count) array.push(i);
}
  return array;
}

  function sum(array){

    let sum = 0;

    for(let value of array){
      sum += value;
    }
    return sum;
  }

console.log(range(1,10));
console.log(sum(range(1,10)));
console.log(range(5, 2, -1));
console.log(range(1, 10, 2));
1 Like

function reverseArray(array) {
var newArray = [ ];
for (var i = array.length - 1; i >= 0; i–) {
newArray.push(array[i]);
}
return newArray;
}

function reverseArrayInPlace(array) {
for (var i = 0; i <= Math.floor((array.length - 1) / 2); i++) {
let el = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = el;
}
return array;
}

1 Like
//Creates an array of numbers from 'start' to 'end', also negative numbers.
//Calculates the sum of the numbers and appends the sum to the last
//element of the returned array.
const myRange = (start, end, step) => {
  let arr = [];
  if (!step) {step = 1};
  if (step < 0) {
    for (let i=end; i >= start; i+=step) {
      arr.push(i);
    };
  } else {
    for (let i=start; i <= end; i+=step) {
      arr.push(i);
    };
  }
  let sum = 0;
  for (value of arr) {
    sum += value;
  }
  arr.push(sum);
  return arr;
};


returnedArr = myRange(1, 10, 1);
console.log(returnedArr);

//Reversing an array into a new array.
const reverseArray = (array) => {
  let newArray = [];
  for (value of array) {
    newArray.unshift(value);
  }
  return newArray;
};

console.log(reverseArray([1,2,3,4,5]));

//Reversing an array in-place.
const reverseArrayInPlace = (array) => {
  for (let i = 0; i < Math.floor(array.length / 2); i++) {
    let temp = array[i];
    array[i] = array[array.length-1-i];
    array[array.length-1-i] = temp;
  }
  return array;
};

console.log(reverseArrayInPlace([1,2,3,4,5]));
1 Like

Hi @daz3d!

Wow!.. you have been very industrious again! :star_struck:

I’m going to reply with some feedback for each exercise separately…

Sum of a Range

You’ve developed a fantastic interface! I particularly like your attention to all the details, such as printing just the right number of commas between the separate array numbers (no more…no less…):

if(i < myArray.length -1) {
   display += ", ";
}

Do you know any CSS? I ask, because it’s clear you like adding specific styling details, such as different text colours. Even though we don’t specifically cover CSS in this course, I’d encourage you to look into it at some stage (if you haven’t already) as it’s much better practice to code your styling in a separate file and import it into your .html document using a <style> element — or if you don’t have much CSS code you can include it all between your <style> tags within your .html document itself (just like how we’re placing our JavaScript code within <script> tags).

CSS isn’t difficult to learn at all. Once you know the basics of how it works by selecting HTML elements with different types of selectors, most of it just involves having a creative flare and good research skills (for looking up and deciding which CSS property/value pairs you need to use to create specific styles).

While reviewing I noticed that the last two lines of code in your doIt function don’t seem to actually do anything (sorry, pun unintentional… :wink:). Am I right in thinking you can just remove them without affecting any of your functionality, or do they serve some purpose that I haven’t realised?

    writeToPage("</div>")
    return;

Finally, there is one additional scenario that your current program cannot yet handle, which the exercise asks you to try to solve: inputs where the step parameter is not given. This requires the inclusion of a default step parameter of either 1 or -1, depending on whether the range is an ascending or descending one. I now challenge you to update your program to include this :muscle:

I’ll send you some feedback on your Reversing an Array, shortly. Sorry for the delay in doing this, but I want to do it justice, and not rush it.

1 Like

Hi @Long,

All of your solutions look suspiciously like the model answers…in fact they’re exactly the same, even down to the variable names… Did you arrive at them all by yourself before looking at the model answers? If so, really well done :muscle:

It’s fine to take a look at the solutions if you need to, before being able to complete the exercises yourself. As long as you give it your best shot first. That’s the most important thing — to really spend time wrestling with it yourself first.

If you did need help from the solutions, then, before moving on, make sure you analyse them, and kind of work backwards from there. This is a really important stage in the learning process. You can learn a lot by working out what the solution does and how it does it, and also how to go about “bridging the gap” from what you managed to do (or not) on your own. As long as you understand the code you’re finally posting, that’s job done! However, it would be nice to see your own versions, even if they are incomplete or don’t execute successfully. We can only help you out by seeing the actual code you’re producing yourself.

Keep on learning! :slightly_smiling_face:

@ivan, @filip

okay, so for the first exercise “sum of a range”, I’m adding some complexity by making it user interactive just for fun. But I’m getting thrown into an infinte loop somehow and it keeps “breaking” the chrome tab such that I can’t reload the page and have to x it out. Where have I gone wrong:

<body>
    <h1>Sum of a Range</h1>
    <input type="text" id="firstNum"> Enter 1st number</input><br><br>
    <input type="text" id="SecondNum"> Enter 2nd number</input><br><br>
    <button id="makeArray">submit numbers</button><br><br>
   <script>
     $("#makeArray").click(function(){
        var numOne = $("#firstNum").val();
        var numTwo = $("#SecondNum").val();
        var numRange = [];
        var iterate = (numOne < numTwo ? 1 : -1);
//this compares the two user input values defined above
        if (iterate >  0){
//iterate will only be either 1 or 0 depending on user input values
          for (let i = numOne; i <= numTwo; i += iterate) numRange.push(i);
//loop which iterates through adding 1 until i > numTwo thus the boolean returns false 
        } else {
          for (let i = numOne; i >= numTwo; i += iterate) numRange.push(i);
//loop which iterates through adding -1 until i < numTwo thus the boolean returns false
        }
        console.log(numRange);
//returning the new array value to console
    });
    </script>

  </body>

Why does this code break into an infinite loop!! I don’t see!

1 Like

you only have half an html file defined here. you are missing the head section perhaps and in the head section you will need to link to the jQuery library unless you forgot to include the rest of your html file

Uncaught ReferenceError: $ is not defined
    at loop1.html:10
1 Like