Chapter 4 - Exercises

I’ve found this solution on the Internet and applied on my needs :shushing_face:
Can someone help me to add the input text to see it on the console.loge?

<body>

    <div id="myDIV" class="header">
      <h2 style="margin:5px">My Favorite Fruits</h2>
      Please Complete your list <input type="text" id="myInput" placeholder="Add...">
      <button onclick="newElement()" class="addBtn">Add</button>
    </div>

    <ul id="fruitlist"></ul>

<script>

          var fruits = ["Apple", "Orange", "Banana"];
          var list = $("#fruitlist");
          $.each(fruits,function(index,value){
            $("<li/>").text(value).appendTo(list);
          });

        // Create a new list item when clicking on the "Add" button
          function newElement() {
          var li = document.createElement("li");
          var inputValue = document.getElementById("myInput").value;
          var t = document.createTextNode(inputValue);
          li.appendChild(t);
          if (inputValue === '') {
            alert("You must write something!");
          } else {
            document.getElementById("fruitlist").appendChild(li);
          }
          document.getElementById("myInput").value = "";

        }
        console.log(fruits);

</script>
</body>
1 Like

The Sum of a Range

  • This is my solution to range:

range

  • And here is sum:

sum

  • I found out, though, that if I call sum(range(1, 10);, the sum cannot access the array that range has created. To make it possible to give range arguments directly to sum, I wrote it like this:

sum range

  • Next part was to create range with a step argument:

rangeStep

  • However, making this work also for negative step took a longer code:

rangeStep negative

Also, to be safe, I defined what happens if somebody enters 0 as step.

Reversing an Array

  • reverseArray is rather simple as it only has to pick a position and put it in the new array:

reverseArray

  • reverseArrayInPlace, however, has to take a position, put it in the back, and then remove the old one. I tried to find a way to save the value, remove the old one and then put the new one in, but I didn’t find a working solution that way. I figured that we can add all positions to the array in reverse order and then remove all the old ones:

reverseArrayInPlace

As we are adding at the back with push, we need to remove from the beginning and for that I found the shift method. We could also do it the other way round with unshift and pop if we rewrite the statements accordingly.

1 Like
  1. The sum of a range
function range (x,y,z){ 
   var rangeArray =[];  
   var z = z ? z : 1;
	  if(x<y){ 
  	    for (i = x; i <= y; i+=z) {
        rangeArray.push(i);
         }
       }
	else {
  	   for (i = x; i >= y; i+=z) {
	     rangeArray.push(i);
	    }
	}
   return rangeArray;
}

function sum (s){
    var total = s.reduce(function(a, b) { 
        return a + b; 
                         }, 0);
        return total;
}



console.log(range(1, 10))
console.log(range(1, 10, 2))
console.log(range(5, 2, -1));
console.log(sum(range(1,10)));
  1. Reversing an array

    function reverseArray(x){ 
      let r = []
      for(i = x.length - 1; i >= 0; i--){
        r.push(x[i]);
      }
    console.log(r)
    }
    
    function reverseArrayInPlace(arrayValue){    
      for(i = arrayValue.length - 1; i > Math.floor((arrayValue.length) / 2); i--){          
        var a = arrayValue[i];
        arrayValue[i] = arrayValue[arrayValue.length - 1 - i];
        arrayValue[arrayValue.length - 1 - i] = a;               
      }
    }
    
    console.log(reverseArray(["A", "B", "C"]));
    // → ["C", "B", "A"];
    let arrayValue = [1, 2, 3, 4, 5];
    reverseArrayInPlace(arrayValue);
    console.log(arrayValue);
    // → [5, 4, 3, 2, 1]
1 Like

create array from start to end

let array = [];

            function range(start,end) {

            for(i = 0; i < end; i++) {

              array.push(start + i)
            }

            return  array;

            }

sum array’s elements

let array = [1, 2, 3, 4];

            function sum() {

            var tot = 0;

            for(i = 0; i < array[array.length - 1]; i++) {

              var tot = tot + array[i];
            }

            return  tot;
            }

bonus range

let array = [];

                function range(start, end, x) {

                for(i = 0; i < end; i = i + Math.abs(x) ) {

                  array.push(start + i)
                }
                return  array;
                }

new array inverted

var array = [1, 2, 3];
      var array1 = [];

            function range() {

            for(i = array.length - 1; i >= 0 ; i = i - 1) {

              array1.push(array[i])
            }

            return  array1;

            }

inverted array

let array = [1, 2, 3];

      var x = array.length

            function range() {

            for(i = array.length - 1; i >= 0 ; i = i - 1) {

              array.push(array[i])
            }

            for(l = 0; l < x ; l++) {

              array.shift(array[0])
            }
            
            return  array;

            }
2 Likes

Excellent answer @MarcisB! Keep up the good work and love your curiosity to find newer topics out of the syllabus.

Happy Learning! :smiley:

2 Likes

Can someone help me to add the text input to add it on the console ?

Hey @kmilo_Mart,

Not sure what you mean but if you want to request a user input from the console, you can try the following:

  • Create a variable that will hold your input;
  • Ask the input to the user.
var input = prompt ("Give me your input");

Please notice that, the input you get will be a string.

Example below:
Schermata 2020-07-23 alle 19.31.25


Schermata 2020-07-23 alle 19.23.32

I hope this is useful. If I misunderstood your question please let me know.

Happy coding,
Dani

2 Likes
  1. The sum of a range
function range(start, end, step){
                if (step == undefined){
                  for (var i = start; i <= end; i++){
                    NewArray.push(i);
                  };
                } else if (step < 0){
                  for (var i = start; i >= end; i--){
                    NewArray.push(i);
                  };
                } else {
                  for (var i = start; i <= end; i = i + step){
                    NewArray.push(i);
                  };
                };
              document.write(NewArray + "<br><br>");
            };

            // range(1, 10);
            // range(1, 10, 2);
             range(5, 2, -1);


            var toPrint = 0;

            function sum(array){
                for (i = 0; i < array.length; i++){
                    toPrint = toPrint + array[i];
                    console.log(array[i]);
                };
              document.write(toPrint);
            };

            sum(NewArray);
type or paste code here
  1. Reversing an array
var start_array = [1,2,3,4,5];
              var new_array = [];

              function reverseArray(array){
                for (var i = 0; i <= array.length-1; i++){
                  new_array.push(array.length-[i]);
                };
                document.write("This is the new array: " + new_array + "<br>");
              };

              document.write("This is the old array: " + start_array + "<br>");
              reverseArray(start_array);


              function reverseArrayInPlace(array){
                for (i = 0; i < (array.length-1)/2; i++){
                  var placeholder = array[array.length-1-i]
                  array[array.length-1-i] = array[i];
                  array[i] = placeholder;
                };
                document.write("This is the reversed array: " + array + "<br>");
              };

              reverseArrayInPlace(new_array);
type or paste code here
1 Like
  1. The sum of range
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;}
  1. Reversing an array
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

Hi @mickymax777, This function seems not to be working. As in , the array does not get reversed. Can you please look into it or if you need any help please let us know.

Happy Learning! :smiley:

1 Like

var array=[1,2,3,4,5] ;

function reverseArrayInPlace(array){

for(var i=-1,i<4,i=i+1){

let el = array[ ];

array[] = array[array.length-i];

}

Return array;

}

Sum of range array:

var range = function(start, end, step) {
var arr = [];
for (var i = start; step > 1 || step === undefined ?
i <= end : i >= end; step ? i = i + step : i++) arr.push(i);
return arr;
};

var sum = function(arr) {
return arr.reduce(function(x, y) {
return x + y;
});
};

Reverse array:

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

var reverseArrayInPlace = function(arr) {
var temp = 0;
for (var i = 0; i < arr.length / 2; i++) {
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;

1 Like

Can someone explain me, in a kinder-garden way how to do this exercises :upside_down_face:. I understand few things, but I have no Idea how to star, it is very abstract for me. I see many of you guys are coming with deferent solutions, I wish I could get my own solution with your help.
Thanks to all.
Have a Good one!

Hey thanks for helping me, It helped me to get what i wanted
Have a good one
:+1:

1 Like

Amazing, for any question let me know!

Happy coding.

Hello.
I am very confuse on how to do the exercise of chapter 4

  1. The sum of a range
  2. Reversing an array
    I got some advances but then I got stocked…
function range(start, end){
        var arr = [];
        for (let i = start; i <= end; i++);
        arr.push(i);
        }
        return arr;
        console.log(i);

I want to console every step I do to see if I’m on the right way, but on the code I just wrote I cannot console…

Thanks for your help.
have a good one

1 Like

Sum of a Range

//I had to watch a tutorial for the solution, still works and could fix the learning.

var range = function(start, end){
					var arr = [];
						cnt = start;
//using a while loop. 
				while (cnt <= end){
					arr.push(cnt);
					cnt++;
				}
				return arr;
			};

			var sum = function(arr) {

				var total = 0;

				while(arr.length > 0){
					total = total + arr.pop();
				}
			return total;	
			};

//Using a For Loop.
				

var sum2 = function(arr){
				var total = 0;

				for(let i = 0; i < arr.length; i++){
					total = total + arr[i];
				}
			return total;	
			};


				console.log(sum(range(1, 10)));
				console.log(sum2(range(1, 10)));
1 Like

// Simplest way I found, after watching some tuts. I really hope it gets easier with time… lol
function ReverseArray(array){
newArray = [];
length = array.length;
for(counter = 0; counter < length; counter++){
newArray[counter] = array[length - counter -1];
}
return newArray;
}

var testArray = [12,23,34,45,56,67,78,89,90,101];

console.log(ReverseArray(testArray));

2 Likes

Splendid @BlogChain_Charles ! It sure will get easier. :slight_smile: Also , Please give your code examples in formatted text. Please see below on how to do so.

prefromatted_text-animated

Happy Learning! :slight_smile:

2 Likes

for sum or an array

var array = [];

function range(start,end){
  let num = end+1 - start;
  for(var i=1;i<=num;i++){
    
    array.push(i);
  }
  return array;
  }
  
  
//console.log(range(1,12));

function sum(array){
  total = 0;
  for(var i in array){
    total = total+array[i];
  }
 return total;
  
}
 //console.log(sum(range(1,11)));
1 Like