× back

Array

                              
let myFriends = ['Ramesh', 22, 'male', 'Arjun', 20, 'male', 'Vishal', true, 52];
               
           

In JavaScript, we have an Array class, and arrays are the prototype of this class. Example ↓

               
let myFriends = new Array; // optional
myFriends = ['Ramesh', 22, 'male', 'Arjun', 20, 'male', 'Vishal', true, 52];
               
           

Traversal in arrays

We use 'for' loop to navigate.

                   
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
for(let i = 0; i < myFriends.length; i++) {
    console.log(myFriends[i]);
}
                   
               

Output ↓

                   
Vinod 
Ramesh
Arjun
Vishal
                   
               

After ES6 we have for..in and for..of loop too

                             
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
for(let ele in myFriends) {
console.log(myFriends[ele]);
}
for(let ele of myFriends) {
console.log(ele);
}
                   
               

Array.prototype.forEach()

  • Calls a function for each element in the array.
                                         
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
myFriends.forEach(function(element, index, array) {
    console.log(element + " index : " + index + " " + array);
});
                       
                   

Searching and Filter in an Array

Array.prototype.indexOf()

  • It returns the first index at which a specified element can be found in the array, or -1 if it is not present.
  • In JavaScript, the prototype property is a feature that allows you to add properties and methods to all instances of a particular object type.
  • In the case of Array.prototype.indexOf(), it is a built-in method that is available on all instances of the Array object type. It returns the first index at which a specified element can be found in the array, or -1 if it is not present.
                       
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.indexOf("Thapa", 3)); 
// second argument is the index number from which it will start searching.
                       
                   

Array.prototype.lastIndexOf()

  • Returns the last index of an element within the array equal to an element, or -1 if none, is found. It search the element last to first.
                        
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.lastIndexOf("Thapa", 3));
                        
                    

Array.prototype.includes()

  • Determines whether the array contains a value, returning true or false as appropriate.
                        
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.includes("Thapa"));
                        
                    

Array.prototype.find()

  • Returns the found element in the array, if some element in the array satisfies the testing function, or undefined if not found.
  • Only problem is that it return only one element.
                                  
const prices = [200, 300, 350, 450, 500, 600];
const findElem = prices.find((currVal) => currVal < 400);
console.log(findElem); // 200

console.log(prices.find((currVal) => currVal > 1400)); // undefined
                       
                   

Array.prototype.findIndex()

  • Returns the found index in the array, if an element in the array satisfies the testing function, or -1 if not found.
                                    
const prices = [200, 300, 350, 450, 500, 600];
console.log(prices.findIndex((currVal) => currVal > 1400)); // -1
                       
                   

Array.prototype.filter()

  • Returns a new array containing all elements of the calling array for which the provided filtering function returns true.
                                   
const prices = [200, 300, 350, 450, 500, 600];
const newPriceTag = prices.filter((elem, index) => {
    return elem > 300;
});
console.log(newPriceTag); // [ 350, 450, 500, 600 ]
                       
                   

How to sort an array

                          
const months = ['March', 'Jan', 'Feb', 'April' , 'Dec', 'Nov'];
console.log(months.sort());

const array1 = [1, 30, 4, 21, 100000, 99];
console.log(array1.sort()); // sorted according to the first digit.

// In JS numbers are sorted as strings,
// "25" is bigger than "100", because "2" is bigger than "1".
// Because of this, the sort() method will produce an incorrect result when sorting numbers.
                   
               

Challenge Time

1- How to sort the numbers in the array in ascending (up) and descending (down) order?

                                  
// Ascending
// we have to create an additional function
compareFunction = (a, b) => {
    // 1. < 0 ... a comes first
    // 2. 0 ... nothing will be changed
    // 3. > 0 ... b comes first

    return a - b;
}

const numbers = [1, 30, 4, 21, 100000, 99];
console.log(numbers.sort(compareFunction));
                       
                   
                       
// Descending 
compareFunction = (a, b) => {
    return b - a; // changes
}

const numbers = [1, 30, 4, 21, 100000, 99];
console.log(numbers.sort(compareFunction));
                       
                   

2- Sort the array ["Banana", "Orange", "Apple", "Mango"] in descending order

                                 
let fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();

// Now we are going to use Array.prototype.reverse()
// The reverse() method reverses an array in place.
// The first array element becomes the last, and the last array element becomes the first.

console.log(fruits);
fruits.reverse();
                       
                   

Perform CRUD

Array.prototype.push()

  • The push() method adds one or more elements to the end of an array and returns the new length of the array.
                       
const animals = ['pigs', 'goats', 'sheep'];
const count = animal.push('chicken');
console.log(count); // 4

animals.push('cats', 'cow', 'tiger');

                   

Array.prototype.unshift()

  • The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
                       
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.unshift('chicken');
console.log(count);
console.log(animals);

animals.unshift('chicken', 'cats','cow');
console.log(animals);

// one more example
const myNumbers = [1,2,3,5];

myNumbers.unshift(4,6);
console.log(myNumbers);
                       
                   

Array.prototype.pop()

  • The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
                             
const plants = ['broccoli', 'cauliflower',  'kale', 'tomato', 'cabbage'];

console.log(plants);
console.log(plants.pop());
console.log(plants);
                       
                   

Array.prototype.shift()

  • The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
                               
const plants = ['broccoli', 'cauliflower',  'kale', 'tomato', 'cabbage'];
console.log(plants);
console.log(plants.shift());
console.log(plants);
                       
                   

Challenge time

Using only one method perform CRUD operation on an array.

  • Given array = ['Jan', 'march', 'April', 'June', 'July']
  • Add 'Dec' at the end of an array.
  • What is the return value of splice method.
  • Update march to March (update).
  • Delete June from given array.

We are going to use Array.prototype.splice() which adds and removes elements from an array.

  • Splice returns an array of all the deleted elements if there are not deleted elements then it returns empty array.
  • If we want to just delete elements from an array then only two arguments are needed: 1- index of element and 2- how many elements from there.
  • If we want to add element after a index then three arguments are passed: 1- index, 2- 0 (as we don't want to delete any element) and 3- element.
  • If we want to replace or update an element then also three arguments are passed 1- index of element you want to update, 2- 0 and 3- updated element
                       
const months = ['Jan', 'march', 'April', 'June', 'July'];
// sol 1
const newMonths = months.splice(months.length, 0, "Dec");

// sol 2
console.log(newMonths); // empty array as not elements are deleted

// sol 3 
if(months.indexOf("march") == -1) {
    console.log("Data not found");
} else {
    months.splice(months.indexOf("march"), 1, "March");
}

// sol 4
if(months.indexOf("June") == -1){
    console.log("Data not found");
} else {
    months.splice(months.indexOf("June"), 1);
}
                       
                   

Map and Reduce method

Array.prototype.map()

  • Returns a new array containing the results (true or false) of calling a function on every element in an array.
  • It returns a new array without mutating the original array.
                                
const array = [1, 4, 8, 16, 25];
// if we want an array which have elements greater than 9 
let newArr = array.map((curEle, index, arr) => {
    return curEle > 9;
});
console.log(newArr); // [false, false, false, true, true]

let newArr2 = array.map((curEle, index, arr) => {
    return `Index no = ${index} and the value is ${curEle} belong to ${arr}`;
})
                       
                   

Challenge Time ⌣

  1. Find the square root of each element in an array.
    let arr = [ 25, 36, 49, 64, 81 ];
  2. Multiply each element by 2 and return only those elements which are greater than 10.
    let arr = [ 2, 3, 4, 6, 8 ];
                                              
// sol 1
let arr = [ 25, 36, 49, 64, 81 ];
let arrSqr = arr.map((curEle) => Math.sqrt(curEle));
console.log(arrSqr); // [ 5, 6, 7, 8, 9 ]
                           
                       
                                              
// sol 2
// here we are going to use chaining method
let arr = [ 2, 3, 4, 6, 8 ];
let arr2 = arr.map((curEle) => {
    return curEle * 2;
}).filter((curEle) => {
    return curEle > 10;
}); 
console.log(arr2); // [ 16, 36, 64 ]
                           
                       

Reduce method

  • Flatten an array, means to convert the 3d or 2d array into a single dimensional array.
  • The reduce() method executes a reduces function (that you provide) on each element of the array, resulting in single output value.
  • The reducer function takes four arguments:
    1. Accumulator
    2. Current value
    3. Current index
    4. Source array
  • Second argument in reduce() method is initial value of the accumulator.
                         
const subMarks = [ 44, 55, 44, 66, 55 ];
const totalMarks = subMarks.reduce((accumulator, curEle, curIn, arr) => {
    return accumulator += curEle;
}, 25);
console.log(totalMarks);
                       
                   

How to flatten an array
Converting 2d and 3d array into one dimensinal array.

                    
const arr = [ 
        ['zone_1', 'zone_2'],
        ['zone_3', 'zone_4'],
        ['zone_5', 'zone_6'],
        ['zone_7', 'zone_8'],
    ]
let flatArr = arr.reduce((accum, currVal) => {
    return accum.concat(currVal)
})
console.log(flatArr);