Day 6. Loops_Exercise


Level 1 / Level 2 / Level 3

👟Level 1.

1) Iterate 0 to 10 using for loop, do the same using while and do while loop.
for (let i = 0; i <= 10; i++) {
  console.log(i);
}

let i = 0;
while (i <= 10) {
  console.log(i);
  i++;
}

let i = 0;
do {
  console.log(i);
  i++;
} while (i <= 10);


2) Iterate 10 to 0 using for loop, do the same using while and do while loop.
for (let i = 10; i >= 0; i--) {
  console.log(i);
}

let i = 10;
while (i >= 0) {
  console.log(i);
  i--;
}

let i = 10;
do {
  console.log(i);
  i--;
} while (i >= 0);

I don’t need semicolons at if else, for loop or while. I do need one after do...while.


3) Iterate 0 to n using for loop.
let n = 15;
for (let i = 0; i <= n; i++) {
  console.log(i);
}

If I want to return the values, I have to declare the variable n.


4) Write a loop that makes the following pattern using console.log():
  #
  ##
  ###
  ####
  #####
  ######
  #######
let string = '#';
for (let i = 1; i <= 6 ; i++) {
    console.log(string.repeat(i));
}

I struggled with this one, wondering how could I print the ‘#’s according to the variable i. I first did some things like console.log('#' * i) but it sure didn’t work and returned NaN(because a string and a number cannot be multiplied). I came up with an idea that I could use repeat() from string method, and it worked.

repeat() takes a number as argument and it returns the repeated version of the string.


5) Use loop to print the following pattern:
0 x 0 = 0
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
9 x 9 = 81
10 x 10 = 100
for (let i = 0; i <= 10; i++) {
  console.log(`${i} x ${i} = ${i*i}`);
}

Don’t forget to end your string template with a back-tick(`)!


5) Use loop to print the following pattern:
 i    i^2   i^3
 0    0     0
 1    1     1
 2    4     8
 3    9     27
 4    16    64
 5    25    125
 6    36    216
 7    49    343
 8    64    512
 9    81    729
 10   100   1000
console.log(`i\ti^2\ti^3`);
for (let i = 0; i <= 10; i++) {
  console.log(`${i}\t${i ** 2}\t${i ** 3}`);
}


7) Use for loop to iterate from 0 to 100 and print only even numbers.
for (let i = 0; i <= 100; i++) {
  if (i % 2 == 0) {
  console.log(i);
  }
}
for (let i = 0; i <= 100; i++) {
  if (i % 2 != 0) {
    continue;
  }
  console.log(i);
}

I made a condition evaluating if the number is an even number, and printed out the values that matches the condition.

Using continue(), I can skip the iteration of odd numbers.


8) Use for loop to iterate from 0 to 100 and print only odd numbers.
for (let i = 0; i <= 100; i++) {
  if (i % 2 != 0) {
  console.log(i);
  }
}
for (let i = 0; i <= 100; i++) {
  if (i % 2 == 0) {
    continue;
  }
  console.log(i);
}


9) Use for loop to iterate from 0 to 100 and print only prime numbers.

I came back from Day 10. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers, which is 1 and itself.

Unlike the similar task I’ve dealt with at Day 7(which was making a function to check whether the input is a prime), this one took me almost 3 hours.


+ Further Study. Break VS Continue

  • break exits the loop as soon as the condition is met. I first thought it’ll stop the iteration only for one loop, but actually it completely ends the loop.

  • continue exits the loop, but it just jumps over one iteration in the loop. It is used to skip one loop iteration.

for (let i = 0; i <= 100; i++) {
  if (i == 0 || i == 1) continue;
  else {
    for (j = 2; j < i; j++) {
      if (j == i - 1) {
        console.log(i);
      }
      if (i % j != 0) {
        continue;
      } else { 
        break;
      }
    }
  }
}

// placing the break first would be more efficient
for (let i = 0; i <= 100; i++) {
  if (i == 0 || i == 1) continue;
  else {
    for (j = 2; j < i; j++) {
      if (j == i - 1) {
        console.log(i);
      }
      if (i % j === 0) {
        break;
      } else { 
        continue;
      }
    }
  }
}


// 'else' part isn't necessary, as the for loop iterates through j
for (let i = 0; i <= 100; i++) {
  if (i == 0 || i == 1) continue;
  else {
    for (j = 2; j < i; j++) {
      if (j == i - 1) console.log(i);
      if (i % j === 0) break;
    }
  }
}


  • Mistakes I’ve been through

I’ve been through numerous cracks due to the nested loop while solving this one. The biggest flaw I had was that I didn’t think of two loops separately enough. I found this out when I wrote down the processes manually on paper.

  • The process that I wanted (as a pseudo-code):

    • i is looping through 0 to 100.

    • For each i , j (ranging from 2 to i-1) would loop inside and divide i.

    • If the remainder of the division is 0(i % j === 0), then i is not a prime number. Move on to next i.

    • If the remainder of the division is not 0(i % j != 0), then move on to next j.

    • i would be a prime when all j(between 2 and i-1 cannot divide i.

In the upper code, I used continue and break. continue skips the statement and moves on to the next iteration. However, break just ends the loop and stops the iteration at all, moving out from the loop.

As soon as one j divides the i, that i must be abandoned and I have to move on to next i. As I can see, the if... else loop is inside the for loop of j. So if I use continue, it doesn’t take me to the next i. It takes me to the next j, which is an unnecessary process. To get out of that i and refresh the for loop of j, I should use break. It’ll immediately stop the for loop of j, and move on to the next i. I didn’t understand this at first, so I wrote something like j = j + 1 at first. It didn’t help at all, and there would be no point of using loops when I were to use that method.

First, I used continue on 0 and 1, because they’re not prime numbers. For the numbers over 2, another for loop of j(dividing numbers) would come in. j would start from 2 and end before i. If the remainder(i % j) isn’t zero, meaning it’s not divisible, continue will skip the iteration and move on to the next j. It’s a same job as j = j + 1. Doing this, when a certain j divides i, that case would go to else and break will be executed. It means that the whole j thing goes away, and the new for loop is executed on the next i.

Over this processes, I can tell a number is a prime when j reaches to i-1. For any integer over 2, i-1 cannot divide i, so I don’t have to explicitly write i % j != 0. The reason I put console.log part at the upper code, is because j gets to i-1 after all the continue is done. When a number is a prime, at the last sequence(when j reaches i-1) the code will be at the start line. If I place it under the else break part, the code will return undefined.

  • A better approach by my friend
for (let number = 2; number <= 100; number++) {
  let isPrime = true;
  for (let i = 2; i <= number - 1; i++) {
    if (number % i === 0) {
      isPrime = false;
      break;
    }
  }
  if (isPrime) console.log(number);
}

Though the idea of using net loops is similar, the boolean was used to determine whether to print the number or not. The variable isPrime is set true at first, and changes to false whenever a divisible number appears.

10) Use for loop to iterate from 0 to 100 and print the sum of all numbers.
const numbers = [];
let sum = 0;
for (let i = 0; i <= 100; i++) {
  numbers.push(i);
  sum += numbers[i]
}
console.log(sum);  //5050

I can put several statements in a block when using for loop. Let’s shorten the code and make it as readable as possible!


11) Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
The sum of all evens from 0 to 100 is 2550. And the sum of all odds from 0 to 100 is 2500.
let sumEvens = 0;
let sumOdds = 0;
for (let i = 0; i <= 100; i++) {
  if (i % 2 == 0) {
    sumEvens += i;
  } else {
    sumOdds += i;
  }
}
console.log(`The sum of all evens from 0 to 100 is ${sumEvens}. And the sum of all odds from 0 to 100 is ${sumOdds}.`);  //The sum of all evens from 0 to 100 is 2550. And the sum of all odds from 0 to 100 is 2500.  


12) Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. Print sum of evens and sum of odds as array.
 [2550, 2500]
let sumEvens = 0;
let sumOdds = 0;

for (let i = 0; i <= 100; i++) {
  if (i % 2 == 0) {
    sumEvens += i;
  } else {
    sumOdds += i;
  }
}
const sumArr = [];
sumArr.push(sumEvens, sumOdds);
console.log(sumArr);  //[2550, 2500]

It was quite hard to grasp the idea on this task, but somehow I got on the way. First, I set a variable to store each sum of even numbers and odd numbers. Then, I used for loop and if else to get the sums of both even and odd numbers. Then, I merged those two sums into one array called sumArr and logged it on the console.


13) Develop a small script which generate array of 5 random numbers.
const randNum = Array(5);
//fill the array with random number between 0 and 10
randNum.fill(Math.floor(Math.random() * 11));
console.log(randNum);  //(5) [2, 2, 2, 2, 2]

I first thought that the array would be filled by 5 different values, but it turned out that Math.random() only assigns one value, and fill() would fill all the elements with that same value.


14) Develop a small script which generate array of 5 random numbers and the numbers must be unique.
const randNum = [];
for (let i = 0; i < 5; i++) {
  randNum[i] = Math.floor(Math.random() * 11);
}
console.log(randNum);  //(5) [0, 10, 1, 0, 9]

To assign unique values to each elements, I used for loop to execute the Math.random() method at each index number.


15) Develop a small script which generate a six characters random id:
5j2khz
let abc = 'abcdefghijklmnopqstuvwxyz0123456789';
const id = [];
for (let i = 0; i < 6; i++) {
    id[i] = abc.charAt(Math.floor(Math.random()*(abc.length+1)));
}
console.log(id.join(''));  //3awg9v

I first thought of using ASCII code, cause the numbers were assigned to each character. But the range of the numbers and lowercase word characters was separated, so I had to find another way. Iwasn’t sure how to get a random character, so I googled it and got the idea from stackoverflow.

The key idea is to use charAt() string method and join() array method. I set a string called abc which contained all lowercase characters and numbers. and I randomly accessed to the character through the index, using Math.random(). Math.floor() floors the number so that the random number wouldn’t have any numbers after the decimal point.

If I hadn’t used join(), the array of single characters would be returned. So, to make the array into string and to make the elments attached, I used join() and put ‘‘(no space) for the parameter.

  • A better approach by my friend
let abc = 'abcdefghijklmnopqstuvwxyz0123456789';
let id = '';
for (let i = 0; i < 6; i++) {
  id += abc.charAt(Math.floor(Math.random()*(abc.length+1)));
}
console.log(id);  //xo6kww

He suggested to assign the variable as a string, and to assign the random character values directly to the empty string. A string can be concatenated with a plus sign(+), so it would get me the same result with the shorter code.


👟Level 2.

1) Develop a small script which generate any number of characters random id:
fe3jo1gl124g
xkqci4utda1lmbelpkm03rba
let n = prompt('What length of id do you want?', 'Enter a number.');
let abc = 'abcdefghijklmnopqstuvwxyz0123456789';
const id = [];
for (let i = 0; i < n; i++) {
    id[i] = abc.charAt(Math.floor(Math.random() * (abc.length + 1)));
}
console.log(id.join(''));

The only difference of this task from the previous one is that the number of times that for loop is executed should be set random. So I set a new variable at the second argument of for loop, which is a condition for the code to be executed. For the variable n, I used prompt to set the number of characters.

Otherwise, if there are certain range of numbers of characters, I can use Math.floor(Math.random()) method for the variable.

//if the range of numbers are set to 0-50
let n = Math.floor(Math.random() * (50 + 1));
let abc = 'abcdefghijklmnopqstuvwxyz0123456789';
const id = [];
for (let i = 0; i < n; i++) {
    id[i] = abc.charAt(Math.floor(Math.random() * ( abc.length + 1)));
}
console.log(id.join(''));


2) Write a script which generates a random hexadecimal number.
'#ee33df'
  • First approach (X):
let hexa = 'abcdef0123456789';
const id = [];
for (let i = 0; i < 6; i++) {
  id[i] = hexa.charAt(Math.floor(Math.random() * 17));
}
console.log(`#${id.join('')}`);  //#2bbc3e

Hexadecimal number is represented by 16 symbols, which are 0-9 and a-f. I slightly changed the code from the upper quiz.

I’m back from Day 7. I found out that the upper code sometimes returns 4 or 5 digits. It was because the number multiplied to Math.random() should be 16, not 17. I wrote in more detail at the similar problem here.

  • Problem solved:
let hexa = 'abcdef0123456789';
const id = [];
for (let i = 0; i < 6; i++) {
  id[i] = hexa.charAt(Math.floor(Math.random() * 16));
}
console.log(`#${id.join('')}`);  //#2ba0ab


3) Write a script which generates a random rgb color number.
rgb(240,180,80)
const rgb = [];
for (let i = 0; i < 3; i++) {
  rgb[i] = Math.floor(Math.random() * 258);
}
console.log(`rgb(${rgb.toString()})`);  //rgb(126,72,120)

A RGB color is set by three numbers each ranging from 0 to 255. I have to randomly assign three numbers from that range to create a random RGB color.

When generating a random rgb color, I should multiply 258, not 256, to set the range between 0 and 255.


4) Using the above countries array, create the following new array.
["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"]
const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
];
const upperCaseCountries = [];
for (let i = 0; i < countries.length; i++) {
  upperCaseCountries[i] = countries[i].toUpperCase();
}
console.log(upperCaseCountries);

To create the array like above, I had to change all the elements to uppercase. I set a new array, and assigned the elements of that array using toUpperCase().


5) Using the above countries array, create an array for countries length’.
[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5]
const countriesLength = [];
for (let i = 0; i < countries.length; i++) {
  countriesLength[i] = countries[i].length;
}
console.log(countriesLength);

I had an error that says ‘i was not defined’ and I found that I put a semicolon after the parenthesis. Let’s be aware of those little things.


6) Use the countries array to create the following array of arrays:
[
  ['Albania', 'ALB', 7],
  ['Bolivia', 'BOL', 7],
  ['Canada', 'CAN', 6],
  ['Denmark', 'DEN', 7],
  ['Ethiopia', 'ETH', 8],
  ['Finland', 'FIN', 7],
  ['Germany', 'GER', 7],
  ['Hungary', 'HUN', 7],
  ['Ireland', 'IRE', 7],
  ['Japan', 'JAP', 5],
  ['Kenya', 'KEN', 5]
]
const countriesArr = [];
for (let i = 0; i < countries.length; i++) {
    countriesArr[i] = [
        countries[i],
        countries[i].slice(0,3).toUpperCase(),
        countries[i].length
        ]
}
console.log(countriesArr);


7) In above countries array, check if there is a country or countries containing the word ‘land’. If there are countries containing ‘land’, print it as array. If there is no country containing the word ‘land’, print ‘All these countries are without land’.
['Finland','Ireland']
const land = [];
for (let i = 0; i < countries.length; i++) {
  if (countries[i].includes('land')) {
    land.push(countries[i]);
  }
}
if (land.length == 0) {
  console.log('All these countries are without land.');
} else {
  console.log(land);
}

I was through a bunch of errors with this because of the ending position of blocks({}). I should decide where to start, or more importantly, where to stop the code. Chunking is important!

I tested if the code works by removing those two elements including ‘land’, and it worked fine.


8) In above countries array, check if there is a country or countries end with a substring ‘ia’. If there are countries end with, print it as array. If there is no country containing the word ‘ia’, print ‘‘These are countries that end without ia.’
['Albania', 'Bolivia','Ethiopia']
const endsWithIa = [];
for (let i = 0; i < countries.length; i++) {
  if (countries[i].endsWith('ia') == true) {
    endsWithIa.push(countries[i]);
  }
}
if (endsWithIa.length == 0) {
  console.log('These are countries that end without ia.')
} else {
  console.log(endsWithIa);
}

To check if the country name ends with ‘ia’, I used endsWith() string method. It takes a substring as its argument and returns a boolean value. Be careful when setting it as a condition.


9) Using the above countries array, find the country containing the biggest number of characters.

I thought I could use Math.max() or sort() to find the country with longest name. I used for loop assuming that there might be more than one country that has the longest name.

  • Using sort()
const countriesLength = [];
for (i = 0; i < countries.length; i++) {
  countriesLength[i] = countries[i].length;
}
countriesLength.sort();
for (i = 0; i < countries.length; i++) {
    if (countries[i].length === countriesLength[countriesLength.length-1]) {
        console.log(countries[i]);
    }
}
  • Using Math.max()
const countriesLength = [];
for (i = 0; i < countries.length; i++) {
  countriesLength[i] = countries[i].length;
}
let max = Math.max(...countriesLength);
for (let i = 0; i < countries.length; i++) {
  if (countries[i].length == max) {
    console.log(countries[i]);
  }
}

Using Math.max(), I had to put numbers as parameters. At first I used toString() inside the Math.max() parameter, but it returned NaN. Strings aren’t numbers. I looked up the document and realized I had to put ... in front of the array name.

To put the elements of an array as an input, use ...


10) Using the above countries array, find the country containing only 5 characters.
['Japan', 'Kenya']

To find the countries with only 5 characters, I thought I could use for...of loop.

for (const element of countries) {
  if (element.length === 5) {
    console.log(element);
  }
}  //Japan Kenya

To print it as an array, I declared a new array and used for loop.

const char5 = [];
for (let i = 0; i < countries.length; i++) {
  if (countries[i].length === 5) {
    char5.push(countries[i]);
  }
}
console.log(char5);  //(2) ['Japan', 'Kenya']

Variable naming rule: It cannot start with a number.


11) Find the longest word in the webTechs array.
const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
];
const techsLength = [];
for (let i = 0; i < webTechs.length; i++) {
  //techsLength.push(webTechs[i].length) will do the same
  techsLength[i] = webTechs[i].length;
}
let max = Math.max(...techsLength);
for (let i = 0; i < webTechs.length; i++) {
  if (webTechs[i].length === max) {
    console.log(webTechs[i])
  }
}  //JavaScript

I think for loop is really helpful when the code has to run through all the elements of an array.

const techsLength = [];
for (let i = 0; i < webTechs.length; i++) {
  techsLength[i] = webTechs[i].length;
}
let max = Math.max(...techsLength);
for (const element of webTechs) {
  if (element.length === max) {
    console.log(element);
  }
}  //JavaScript

At first I used another for loop at the end, but I thought using for...of loop would be more readable. Before that, I tried to shorten the code by merging two for loops, but it didn’t work. As the code runs from top to bottom, each variable should be assigned a value first.

I’m back from Day 14. Because I’ve learned to use higher function, I can use nested loop and a spread syntax(...) to solve this task with a shorter code.

let max = Math.max(...webTechs.map((skill) => skill.length));
for (const element of webTechs) {
  if (element.length === max) {
    console.log(element);
  }
}
// JavaScript

First I modified the array to an array containing each element’s length, using map(). Then I used a spread syntax to spread the elements in the parameter of Math.max().

12) Use the webTechs array to create the following array of arrays:
[["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]]
const techLength = [];
for (let i = 0; i < webTechs.length; i++) {
  techLength[i] = [
    webTechs[i],
    webTechs[i].length
    ]
}
console.log(techLength);


13) An application created using MongoDB, Express, React and Node is called a MERN stack app. Create the acronym MERN by using the array mernStack.
const mernStack = ['MongoDB', 'Express', 'React', 'Node'];
for (const element of mernStack) {
  console.log(element[0].toUpperCase());
}  //M E R N

To print out the acronym as a string:

const mernStack = ['MongoDB', 'Express', 'React', 'Node'];
const acronym = [];
for (const element of mernStack) {
  acronym.push(element[0].toUpperCase());
}
console.log(acronym.join(''));


14) Iterate through the array, [“HTML”, “CSS”, “JS”, “React”, “Redux”, “Node”, “Express”, “MongoDB”] using a for loop or for of loop and print out the items.
  • Using for loop
const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
];
for (let i = 0; i < webTechs.length; i++) {
  console.log(webTechs[i]);
}
  • Using for...of loop
for (const element of webTechs) {
  console.log(element);
}


15) This is a fruit array , [‘banana’, ‘orange’, ‘mango’, ‘lemon’] reverse the order using loop without using a reverse method.
const fruit = ['banana', 'orange', 'mango', 'lemon'];
const reverseFruit = [];
for (let i = 0; i < fruit.length; i++) {
  reverseFruit.unshift(fruit[i]);
}
console.log(reverseFruit);
//(4) ['lemon', 'mango', 'orange', 'banana']

I set a new array, and used unshift() to add the elements from the original array backwards. I thought using unshift() was similar to LIFO(last in, first out) method. On the contrary, push() would be similar to FIFO(first in, first out) method.


16) Print all the elements of array as shown below.
const fullStack = [
  ['HTML', 'CSS', 'JS', 'React'],
  ['Node', 'Express', 'MongoDB']
]
  HTML
  CSS
  JS
  REACT
  NODE
  EXPRESS
  MONGODB


const fullStack = [
  ['HTML', 'CSS', 'JS', 'React'],
  ['Node', 'Express', 'MongoDB']
];
//fullStack.toString().split(','); will do the same
const fullStackArr = fullStack.join().split(',');
for (const element of fullStackArr) {
  console.log(element.toUpperCase());
}

I found out that either join() or toString() removes the inner array of the array. But it returns as a string(HTML,CSS,JS,React,Node,Express,MongoDB), so I decided to use split() string method to cut each element and make it to another array. Then I changed each element of the new array to uppercase, using for...of loop.

  • A better approach by my friend
for (let i = 0; i < fullStack.length; i++) {
  for (let j = 0; j < fullStack[i].length; j++) {
    console.log(fullStack[i][j].toUpperCase());
  }
}

I can use nested loop to do the job in a shorter code. As the array fullStack has two arrays as its elements, another loop is used to go through the elements inside the elements, and to uppercase them. Though I have to be cautious when using nested loops, but I think this one is neat.


👟Level 3.

1) Copy countries array(Avoid mutation).
const countriesCopy = [...countries];
const countriesCopy = [];
for (let i = 0; i < countries.length; i++) {
  countriesCopy[i] = countries[i];
}
const countriesCopy = countries.slice();

After searching, I found that there are many ways to clone an array in JavaScript and to avoid array mutation in JavaScript.


2) Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries.
const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
];
const countriesCopy = [];
for (let i = 0; i < countries.length; i++) {
  countriesCopy.push(countries[i]);
}
const sortedCountries = countriesCopy.sort();

I’m not quite sure about the idea of creating a copy of array which does not modify the original. On the articles I linked above, there were ‘shallow copy’ and ‘deep copy’. I’m not fully aware of all the methods that were mentioned, but I think I’ll get to learn it later.


3) Sort the webTechs array and mernStack array.
const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
]
const mernStack = ['MongoDB', 'Express', 'React', 'Node']

console.log(webTechs.sort());  //(7) ['CSS', 'HTML', 'JavaScript', 'MongoDB', 'Node', 'React', 'Redux']
console.log(mernStack.sort());  //(4) ['Express', 'MongoDB', 'Node', 'React']


4, 6) Extract all the countries contain the word ‘land’ from the countries array and print it as array.
const land = [];
for (const element of countries) {
  if (element.includes('land')) {
    land.push(element);
  }
}
console.log(land);
//(11) ['Finland', 'Iceland', 'Ireland', 'Marshall Islands', 'Netherlands', 'New Zealand', 'Poland', 'Solomon Islands', 'Swaziland', 'Switzerland', 'Thailand']


5) Find the country containing the hightest number of characters in the countries array.
const countriesLength = [];
for (let i = 0; i < countries.length; i++) {
  countriesLength[i] = countries[i].length;
}
let max = Math.max(...countriesLength);
for (const element of countries) {
  if (element.length === max) {
    console.log(element);
  }
}  //Central African Republic / East Timor (Timor Timur)


7) Extract all the countries containing only four characters from the countries array and print it as array.
const char4Countries = [];
for (const element of countries) {
  if (element.length === 4 ) {
    char4Countries.push(element);
  }
}
console.log(char4Countries);
//(10) ['Chad', 'Cuba', 'Fiji', 'Iran', 'Iraq', 'Laos', 'Mali', 'Oman', 'Peru', 'Togo']


8) Extract all the countries containing two or more words from the countries array and print it as array.

I thought ‘two or more words’ not as ‘two or more characters’ but rather as ‘having more than one space’.

const wordsCountries = [];
for (const element of countries){
  if (element.includes(' ')) {
    wordsCountries.push(element);
  }
}
console.log(wordsCountries);
//(35) ['Antigua and Barbuda', 'Bosnia and Herzegovina', 'Burkina Faso', 'Cape Verde', 'Central African Republic', 'Congo (Brazzaville)', 'Costa Rica', "Cote d'Ivoire", 'Czech Republic', 'Dominican Republic', 'East Timor (Timor Timur)', 'El Salvador', 'Equatorial Guinea', 'Gambia, The', 'Korea, North', 'Korea, South', 'Marshall Islands', 'New Zealand', 'Papua New Guinea', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Serbia and Montenegro', 'Sierra Leone', 'Solomon Islands', 'South Africa', 'Sri Lanka', 'Trinidad and Tobago', 'United Arab Emirates', 'United Kingdom', 'United States', 'Vatican City']


9) Reverse the countries array and capitalize each country and store it as an array.

Since the countries array was already sorted, I only used reverse().

At first I tried this one, but it didn’t work. I guess that it’s because I didn’t specify which element I would uppercase.

const countriesReverse = countries.reverse();
for (let element of countriesReverse) {
  element = element.toUpperCase();
}
console.log(countriesReverse);

The code below worked fine.

const countriesReverse = countries.reverse();
for (let i = 0; i < countries.length; i++) {
  countriesReverse[i] = countriesReverse[i].toUpperCase();
}
console.log(countriesReverse);

Here, I declared a new array for the capitalized country names.

const countriesReverse = countries.reverse();
const countriesCap = [];
for (let i = 0; i < countries.length; i++) {
  countriesCap.push(countriesReverse[i].toUpperCase());
}
console.log(countriesCap);


Leave a comment