Day 5 Of #30DaysOfJavaScript

Day 5 Of #30DaysOfJavaScript

ยท

7 min read

Introduction

Hey folks, I hope that you must have read my Day 4 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.

Arrays

In contrast to variables, an array can store multiple values. Each value in an array has an index, and each index has a reference in a memory address. Each value can be accessed with the help of methods of indexing. The index of an array starts from zero, and the index of the last element is less than one from the length of the array.

An array is a collection of different data types which are ordered and mutable. An array allows for storing duplicate elements and different data types. An array can be empty, or it may have different data type values.

How To Create An Empty Array?

  • Using Array Constructor:

Syntax:

const arr = Array()

console.log(arr); // []
  • Using Square Brackets([]):

Syntax:

const arr = []
console.log(arr);

How To Create An Array With Values?

For Example:

const numbers = [0, 3.14, 9.81, 37, 98.6, 100]
const fruits = ['banana', 'orange', 'mango', 'lemon'] 
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] 
const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] 
const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] 
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] 

// Print the array and its length

console.log('Numbers:', numbers);
console.log('Number of numbers:', numbers.length);

console.log('Fruits:', fruits);
console.log('Number of fruits:', fruits.length);

console.log('Vegetables:', vegetables);
console.log('Number of vegetables:', vegetables.length);

console.log('Animal products:', animalProducts);
console.log('Number of animal products:', animalProducts.length);

console.log('Web technologies:', webTechs);
console.log('Number of web technologies:', webTechs.length);

Output:

Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
Number of numbers: 6

Fruits: ['banana', 'orange', 'mango', 'lemon']
Number of fruits: 4

Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Number of vegetables: 5

Animal products: ['milk', 'meat', 'butter', 'yoghurt']
Number of animal products: 4

Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
Number of web technologies: 7
  • Array With Different Data Types:

For Example:

const arr = [
    'Shivank',
    250,
    true,
    { country: 'India', city: 'New Delhi' },
    { skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] }
] 
console.log(arr);

How To Create An Array Using Split Method?

For Example:

let js = 'JavaScript'
const charsInJavaScript = js.split('')

console.log(charsInJavaScript); // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]

let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon';
const companies = companiesString.split(',')

console.log(companies); // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"]
let txt =
  'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
const words = txt.split(' ');

console.log(words);
// The text has special characters think how you can just get only the words
// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"]

How To Access Array Items Using Indexing?

An element in an array is accessed using indexing. An array index starts from 0.

For Example 1:

const fruits = ['banana', 'orange', 'mango', 'lemon'];
let firstFruit = fruits[0] // We are accessing the first item using its index

console.log(firstFruit); // banana

secondFruit = fruits[1]
console.log(secondFruit); // orange

let lastFruit = fruits[3]
console.log(lastFruit); // lemon
// Last index can be calculated as follows

let lastIndex = fruits.length - 1
lastFruit = fruits[lastIndex]

console.log(lastFruit); // lemon

For Example 2:

const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // Set of numbers

console.log(numbers.length); // => To know the size of the array, which is 6
console.log(numbers); // -> [0, 3.14, 9.81, 37, 98.6, 100]
console.log(numbers[0]); //  -> 0
console.log(numbers[5]); //  -> 100

let lastIndex = numbers.length - 1;
console.log(numbers[lastIndex]); // -> 100

For Example 3:

const shoppingCart = [
  'Milk',
  'Mango',
  'Tomato',
  'Potato',
  'Avocado',
  'Meat',
  'Eggs',
  'Sugar'
] // List of food products

console.log(shoppingCart) // -> All shoppingCart in array
console.log(shoppingCart[0]) //  -> Milk
console.log(shoppingCart[7]) //  -> Sugar

let lastIndex = shoppingCart.length - 1;
console.log(shoppingCart[lastIndex]) //  -> Sugar

How To Modify An Array Element?

For Example:

const numbers = [1, 2, 3, 4, 5];
numbers[0] = 10 // Changing 1 at index 0 to 10
numbers[1] = 20  // Changing  2 at index 1 to 20

console.log(numbers); // [10, 20, 3, 4, 5]

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

countries[0] = 'Afghanistan';  // Replacing Albania by Afghanistan
let lastIndex = countries.length - 1
countries[lastIndex] = 'Korea'; // Replacing Kenya by Korea

console.log(countries);

What Are The Methods To Manipulate An Array?

There are different ways to manipulate an array. Some of the methods are:

  1. Creating Static Values: It is used for filling the array with Static Values.

For Example:

const arr = Array() // It creates an an empty array
console.log(arr);

const eightXvalues = Array(8).fill('X') // It creates eight element values filled with 'X'
console.log(eightXvalues); // ['X', 'X','X','X','X','X','X','X']

const eight0values = Array(8).fill(0) // It creates eight element values filled with '0'
console.log(eight0values); // [0, 0, 0, 0, 0, 0, 0, 0]

const four4values = Array(4).fill(4) // It creates 4 element values filled with '4'
console.log(four4values); // [4, 4, 4, 4]
  1. Concatenating Arrays: It is used for the joining of two arrays.

For Example:

const firstList = [1, 2, 3]
const secondList = [4, 5, 6]
const thirdList = firstList.concat(secondList);

console.log(thirdList) // [1, 2, 3, 4, 5, 6]
  1. Getting Array Length: It is used for getting the size of the array.

For Example:

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.length); // -> 5 is the size of the array
  1. Getting The Index Of An Array: It is used to check if an item exists in an array.

For Example:

const numbers = [1, 2, 3, 4, 5]

console.log(numbers.indexOf(5)); // -> 4
console.log(numbers.indexOf(0)); // -> -1
console.log(numbers.indexOf(1)); // -> 0
console.log(numbers.indexOf(6)); // -> -1
  1. Getting The Last Index Of An Element In An Array: It gives the value of the last index of an array.

For Example:

const numbers = [1, 2, 3, 4, 5, 3, 1, 2]

console.log(numbers.lastIndexOf(2)); // 7
console.log(numbers.lastIndexOf(0)); // -1
console.log(numbers.lastIndexOf(1)); //  6
console.log(numbers.lastIndexOf(4)); //  3
console.log(numbers.lastIndexOf(6)); // -1
  1. Checking An Array: It is used to check if the Data Type is an array or not.

For Example:

const numbers = [1, 2, 3, 4, 5]
console.log(Array.isArray(numbers)); // true

const number = 100
console.log(Array.isArray(number)); // false
  1. Slicing Array Elements: It is used to cut out multiple items in the range. It takes two parameters: starting and ending position. It doesn't include the ending position.

For Example:

const numbers = [1,2,3,4,5]

console.log(numbers.slice()); // -> It copies all  item
console.log(numbers.slice(0)); // -> It copies all  item
console.log(numbers.slice(0, numbers.length)); // It copies all item
console.log(numbers.slice(1,4)); // -> [2,3,4] // It doesn't include the ending position
  1. Adding An item to an Array using push: It is used for adding an item to the end of an array.

Syntax:

const arr  = ['item1', 'item2','item3']
arr.push('new item')
console.log(arr);
// ['item1', 'item2','item3','new item']

For Example:

let fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.push('apple')
console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple']

fruits.push('lime')
console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
  1. Removing The End Element Using Pop: It is removing an item in the end.

For Example:

const numbers = [1, 2, 3, 4, 5]
numbers.pop() // -> Removes one item from the end
console.log(numbers); // -> [1,2,3,4]
  1. Reversing An Array: It is used for reversing the order of any array.

For Example:

const numbers = [1, 2, 3, 4, 5]
numbers.reverse() // -> Reversing the array order
console.log(numbers); // [5, 4, 3, 2, 1]

numbers.reverse()
console.log(numbers); // [1, 2, 3, 4, 5]
  1. Sorting Of Elements In An Array: It is used for arranging array elements in ascending order.

For Example:

const webTechs = [ 'HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node', 'MongoDB'
];

webTechs.sort()
console.log(webTechs); // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"]

webTechs.reverse() // After sorting we can reverse it
console.log(webTechs); // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]

2-Dimensional Arrays

2-D Arrays or Array of arrays is a way of storing array Data Type inside another array. An array can store different Data Types including an array itself.

For Example:

const firstNums = [1, 2, 3]
const secondNums = [1, 4, 9]

const arrayOfArray =  [[1, 2, 3], [1, 2, 3]]
console.log(arrayOfArray[0]); // [1, 2, 3]

 const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
 const backEnd = ['Node','Express', 'MongoDB']
 const fullStack = [frontEnd, backEnd]
 console.log(fullStack); // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
 console.log(fullStack.length); // 2
 console.log(fullStack[0]); // ["HTML", "CSS", "JS", "React", "Redux"]
 console.log(fullStack[1]); // ["Node", "Express", "MongoDB"]

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer ๐Ÿค”!

ย