Day-5 of JS

·

5 min read

Today we are going to learn Arrays, I used to understand arrays as box..which hold something. Let us dive deep to know what more we can do with arrays in JS.

We can create an empty array, arrays with values and arrays with different datatypes. Then we have different ways to manipulate our data in defined arrays. Lets do some exercises, because we learn by doing.

  1. Declare an empty array;

  2. Declare an array with more than 5 number of elements

  3. Find the length of your array.

  4. Get the first item, the middle item and the last item of the array

const emptyArray = [];
var arrayVal= Array(5);
console.log(arrayVal.length) //5
arrayVal=[1,2,3,4,5];
arrayVal[0];
arrayVal[2];
arrayVal[4];
  1. Declare an array called mixedDataTypes, put different data types in the array and find the length of the array. The array size should be greater than 5
var mixedDataTypes = [
"10",10,"Isha",10.00,true,{skills:[Javascript, Html, Css]}
];
mixedDataTypes.length;
typeof(mixedDataTypes[5]); //Object
  1. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon
var itCompanies = ["Facebook", "Google", "Microsoft", 
"Apple", "IBM","ORacle","Amazon"]
  1. Print the array using console.log()
console.log(itCompanies);
  1. Print the number of companies in the array in the first company, middle and last company

  2.   itCompanies[0];
      itCompanies[itCompanies.length/2];
      itCompanies[itCompanies.length -1]; //used to access last index
    
  3. Print out each company and Change each company name to uppercase one by one and print them out

  4.   console.log(itCompanies[0].toUpperCase())
      console.log(itCompanies[1].toUpperCase())
      console.log(itCompanies[2].toUpperCase())
      console.log(itCompanies[3].toUpperCase())
      console.log(itCompanies[4].toUpperCase())
      console.log(itCompanies[5].toUpperCase())
      console.log(itCompanies[6].toUpperCase())
      console.log(itCompanies[7].toUpperCase())
      //Alternative method
      const changeCase  = itCompanies.map(element=>element.toUpperCase())
    
  5. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.

  6.   console.log(itCompanies.split(","))
    
  7. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is not found

  8.  itCompanies.includes("Facebook")?"Facebook":"Company not found"
    
  9. Filter out companies which have more than one 'o' without the filter method

  10. var itCompanies = ["Facebook", "Google", "Microsoft", 
    "Apple", "IBM","ORacle","Amazon"]
    let filtered = [];
    let count =0;
    for(let i = 0; i<itCompanies.length;i++){
        for(let j = 0; i<itCompanies[i].length; j++){
            if(itCompanies[i][j].toLowerCase() ==="o") count++;
        }
        if(count<=1) filtered.push(itCompanies[i]);
    }
    console.log(filtered)
    
  11. Sort the array using sort() method

  12. itCompanies.sort()
    
  13. Reverse the array using reverse() method

  14. itCompanies.reverse()
    
  15. Slice out the first 3 companies from the array

  16. //Slice method takes two parameters, start and end position
    itCompanies.slice(0,2)
    
  17. Slice out the last 3 companies from the array

  18. itCompanies.slice(itCompanies.length-3,itCompanies.length)
    
  19. Slice out the middle IT company or companies from the array

  20. itCompanies.slice(Math.floor(itCompanies.length/2),(Math.floor(itCompanies.length/2))+1)
    
  21. Remove the first IT company from the array

  22. //shift: Removing one array element in the beginning of the array.
    itCompanies.shift();
    
  23. Remove the middle IT company or companies from the array

  24. itCompanies.pop(Math.floor(itCompanies.length/2))
    
  25. Remove the last IT company from the array

  26. itCompanies.pop()
    
  27. Remove all IT companies

  28. //if it is let and var, reassign it 
    itCompanies = [];
    //if its const
    itCompanies.length =0;
    

    //Create a separate countries.js file and store the countries array in to this file, create a separate file web_techs.js and store the webTechs array in to this file. Access both file in main.js file

Added this in VS Code. I had two errors while coding this, one i did not add all the script file in html, did not add "type:module" and last bonus one did not use ".js" in the path

Also i can see my script js on browser like the codes. See the image below.

Exercise-2

//Create a separate countries.js file and store the countries array in to this file, create a separate file web_techs.js and store the webTechs array in to this file. Access both file in main.js file

import  {webTechs}  from "./web_techs.js";
import { countries } from "./countries.js";

console.log(countries);
console.log(webTechs);
console.log("1");
let text =
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
text.replace(/[^\w\s]|_/g,"");
let words = text.split(" ")
console.log(words)
console.log(words.length)

const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
console.log(shoppingCart);
shoppingCart.push("Ginger") //Add in the array
console.log("Add Ginger : "+shoppingCart);
shoppingCart.pop() //Remove the last element
console.log("Removed Ginger : "+shoppingCart);
shoppingCart.pop('Milk')
console.log(shoppingCart);

//add 'Meat' in the beginning of your shopping cart if it has not been already added
shoppingCart.unshift("Meat");
console.log("Adding Meat at 0:" + shoppingCart);
//add Sugar at the end of you shopping cart if it has not been already added
shoppingCart.push("Sugar")
console.log("Add sugar at the end:"+shoppingCart);
//remove 'Honey' if you are allergic to honey
shoppingCart.pop('Honey')
console.log("Remove Honey:"+shoppingCart);
//modify Tea to 'Green Tea'
shoppingCart[shoppingCart.length-1]='Green Tea';
console.log(shoppingCart);
//
//In countries array check if 'Ethiopia' exists in the array if it exists 
//print 'ETHIOPIA'. If it does not exist add to the countries list.
countries.includes("ETHIOPIA")?"ETHIOPIA": countries.push("Ethiopia")
console.log(countries);

//In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. 
//If it does not exist add Sass to the array and print the array.
console.log(webTechs.includes('Sass')?"Sass":'Sass is a CSS preprocess');

//Concatenate the following two variables and store it in a fullStack variable.
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
const backEnd = ['Node','Express', 'MongoDB']
const fullStack = [...frontEnd,...backEnd]
console.log(fullStack)

Exercise: Level

The following is an array of 10 students ages:

const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]

  • Sort the array and find the min and max age
const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24];
console.log(ages.sort((a,b)=>a-b))
let minAge = Math.min(...ages);
console.log("Minimum Age : "+ minAge);
let maxAge = Math.max(...ages);
console.log("Maximum Age : "+maxAge);
/Find the median age(one middle item or two middle items divided by two)
let median;
if(ages.length % 2 ===0){
    median=(((ages.length/2-1)+ages.length/2)/2)
} else {
    median = Math.floor(ages.length/2)
}
console.log("Median:"+median);

//Find the average age(all items divided by number of items)
let sum = ages.reduce((acc,currVal)=>acc+currVal,0)
let average = sum/ages.length
console.log("Average :",average)

//Age Range
const ageRange = Number(maxAge-minAge)
console.log("Age Range",ageRange)