JavaScript Array and Array Methods

JavaScript Array and Array Methods

In this article, we will discuss about JavaScript array and their various methods.

JavaScript Arrays

  • In JavaScript, an array is an ordered list of values. Each value is called an element specified by an index.

  • JavaScript Array is used to store multiple elements in a single variable.

  • in JavaScript array is a single variable that stores multiple elements.

  • In JavaScript, an array can hold values of mixed types. For example, we can have an array that stores elements with the types number, string, boolean, and null.

  • The size of an array is dynamic and auto-growing. We don’t need to specify the array size up front.

Creating JavaScript Array

  • By Array Literal: We can declare an array while initializing.
// it creates an array with 3 strings and 2 integer elements
var array1= ["Madhav","Sahi","MadhavSahi",100,10];
  • By constructor(New keyword):
/*Creates an array having elements 10, 20, 30, 40, 50*/
var nums = new Array(10, 20, 30, 40, 50);

//Creates an array of 5 undefined elements
var nums2 = new Array(5);

Accessing an Array

  • JavaScript arrays are zero-based indexed.

  • The first element of an array starts at index 0, the second element starts at index 1, and so on.

  • To access an element in an array, we have to specify an index in the square brackets []:

//we can access using arrayname[indexnumber]
let values= ['Hi', 'Hello', 'Okay'];
console.log(values[0]); // 'Hi'
console.log(values[1]); // 'Hello'
console.log(values[2]); // 'Okay'

//we can add/replace any value using index number
values[1]='Hey';
console.log(values); // [ 'Hi','Hey','Okay']

JavaScript Array Methods

.length

  • It is used to get the length/size of an array.
let values= ['Hi', 'Hello', 'Okay','Madhav','Sahi'];
let len = values.length; 
console.log("Lenth of this array is " + len);
//Output:
Lenth of this array is 5

.push()

  • It is used to add values at the end of an array.

  • Syntax is - array1.push(element1,element2..so on)

  • It modifies the orginal array only.

let array1=['hi','hii','hello','okay',5,6,'ok'];
array1.push(100,299);
console.log(array1);
//Output
[ 'hi','hii','hello','okay',5,6,'ok',100,299 ]

.pop()

  • It is used to remove the last element of an array.

  • This method does not accept any parameter.

  • It will return the last element of the array.

  • If the array is empty, then this function returns undefined.

  • It modifies the original array.

    let arr = [34, 234, 567, 4]; 
    // Popping the last element from the array
    var popped = arr.pop();
    console.log(popped);
    console.log(arr);

    //Output:
    4
    [34,234,567]

.shift()

  • It is used to remove the first element of the array.

  • This method does not accept any parameter.

  • It will return the first element of the array.

  • If the array is empty, then this function returns undefined.

  • It modifies the original array.

    let arr = [34, 234, 567, 4]; 
    // Popping the first element from the array
    var shifted= arr.shift();
    console.log(shifted);
    console.log(arr);

    //Output:
    34
    [234,567,4]

.unshift()

  • unshift() Method is used to add one or more elements to the beginning of the given array.

  • It works as : array.unshift("element_1","element_2",...so on)

  • This function returns the new length of the array after inserting the arguments at the beginning of the array.

  • This function increases the length of the existing array by the number of elements added to the array.

  • If the array is empty, then this method returns undefined.

  • It modifies the original array.

        var array = ["GFG", "Geeks", "for", "Geeks"];
        // Checking for condition in array
        var value = array.unshift("GeeksforGeeks");
        console.log(value);
        console.log(array);

        //Output
        5
        ["GeeksforGeeks","GFG","Geeks","for","Geeks"]

.concat()

  • Array concat() method is used to merge two or more arrays.

  • It works as - array1.concat(array2);

  • This method does not alter the original arrays passed as arguments.

  • This method returns a newly created array that is created after merging all the arrays passed to the method as arguments.

let arr1 = [34,234,56]; 
let arr2 = [1,2,3,4];
let arr3 = arr1.concat(arr2);
arr3.push(100);
console.log(arr3); 

//Output
[34,234,56,1,2,3,4,100]

.includes()

  • It works as array1.includes(element,start-index)

  • It returns a boolean value.

  • The includes method checks if an array contains a specified element or not.

  • The syntax is - array1.includes(valueToFind, fromIndex). 2nd parameter is optional with a default value of 0.

  • The method is case-sensitive for string values.

let arr1 = [34,234,56]; 
let arr2 = [1,2,3,4,'python']; 
let ans = arr1.includes(34);
let ans2 = arr2.includes('Python');
console.log(ans);
console.log(ans2);

//Output
true
false

.splice()

  • The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

  • Syntax - array1.splice(index, remove_count, item1,itme2,..itemN )

  • It modifies the original array in place.(it is a mutator method).

  • It returns the list of removed items. In case there is no removed array it returns an empty array.

  • If remove-count is 0 or negaive, then it deletes all the elements after the index .

let languages1 = ["JavaScript", "Python", "Java", "Lua"];
// does not removes, only appends to the end
let removed1 = languages1.splice(5, 2, "C++");
console.log(removed1); // []
console.log(languages1); // ["JavaScript", "Python", "Java", "Lua", "C++"]

let languages2 = ["JavaScript", "Python", "Java", "Lua"];
// removes everything from start
let removed2 = languages2.splice(1);
console.log(removed2); // [ "Python", "Java", "Lua" ]
console.log(languages2); // [ "JavaScript" ]

let languages3 = ["JavaScript", "Python", "Java", "Lua"];
// remove none & add 3 more element
let removed3 = languages3.splice(1, -2, "Swift", "Scala", "Go");
console.log(removed3); // [ ]
console.log(languages3); // [ "JavaScript", "Swift", "Scala", "Go" ]

.slice()

  • The Javascript arr.slice() method returns a new array containing a portion of the array on which it is implemented.

  • The original remains unchanged.

  • Syntax is - array1.slice(start,end)

  • Start is the starting index of selection. By default it is 0.

  • End is the ending index of selection. By default it is end index of array. It is exclusive.

        //Original Array1
        var array1 = [23,56,87,32,75,13];
        //Extracted array
        var new_array1 = array1.slice();
        console.log(array1);
        console.log(new_array1);

        //Original Array2
        var array2 = [23,56,87,32,75,13];
        //Extracted array
        var new_array2 = array2.slice(3);
        console.log(array2);
        console.log(new_array2);

        //Original Array3
        var array3 = [23,56,87,32,75,13];
        //Extracted array
        var new_array3 = array3.slice(2,5);
        console.log(array3);
        console.log(new_array3);

        //Output
        array1 = [23,56,87,32,75,13]
        new_array1 = [23,56,87,32,75,13]

        array2 = [23,56,87,32,75,13]
        new_array2 = [32,75,13]

        array3 = [23,56,87,32,75,13]
        new_array3 = [87,32,75]

.split()

  • The split() method splits a string into an array of substrings.

  • Syntax is - string1.split(' ');

  • The split() method returns the new array.

  • The split() method does not change the original string.

  • If ('') is used as separator, the string is split between words.

let names="Madhav Sahi";

let array1=names.split('');
console.log(array1);

let array2=names.split(' ');
console.log(array2);

let array3=names.split('a');
console.log(array3);

let array4=names.split('z'); //this character doesn't exist in string
console.log(array4);

//Output
array1 = ['M', 'a', 'd', 'h','a', 'v', ' ', 'S','a', 'h', 'i']  
array2 = ['Madhav', 'Sahi']
array3 = [ 'M', 'dh', 'v S', 'hi' ]
array4 = [ 'Madhav Sahi' ]

.map()

  • The map() method creates a new array with the results of calling a function for every array element.

  • JavaScript Array type provides the map() method that allows us to transform the array elements in a cleaner way.

  • The map() method calls a callback function on every element of an array and returns a new array that contains the results.

  • Syntax is - array1.map(callback,thisArg)

  • It doesn't modify the existing array.

let numbers = [16, 25, 36];
let results = numbers.map(Math.sqrt);
console.log(results);

let circles = [10, 30, 50];
function circleArea(radius) 
{
    return Math.floor(Math.PI * radius * radius);
    //it returns new array having all the new elements in new array
}
let areas = circles.map(circleArea); //it will pass each value from circles array to the circleArea function
console.log(areas);
//The map() method will call the circleArea function on each element of the circles array and return a new array with the elements that have been transformed.

//Output
[4, 5, 6]
[314, 2827, 7853]

.indexOf()

  • The indexOf() method returns the first index of occurrence of an array element, or -1 if it is not found.

  • It works as - array1.indexOf("element")

let array9=['Madhav',"madhav sahi",9,22,"Madhav Sahi",'Sahi','madhav'];
console.log(array9.indexOf("Madhav Sahi")); // it will return first index;
console.log(array9.indexOf("Madhavs")); // it will return -1 when not found;

//Output
4
-1

.lastIndexOf()

  • The .lastIndexOf() method returns the last index of occurrence of an array element, or -1 if it is not found.

  • It works as - array1.lastIndexOf("element").

let array9=['Madhav',"madhav sahi",9,22,"Madhav Sahi",'Sahi','madhav',9,22];
console.log(array9.lastIndexOf(9)); // it will return last index;
console.log(array9.lastIndexOf("Madhavs")); //it will return -1 when not found;

//Output
7
-1

Array.isArray()

  • The method checks whether the passed argument is an array or not.

  • The syntax is - Array.isArray(var_name)

  • It returns true or false depending on whether the variable is an array or not.

let number=9;
let array3 = ['madhav','hello',4,100];
console.log(Array.isArray(array3)); // it will return true becuase array3 is an array
console.log(Array.isArray(number)); // it will return false becuase numberis not an array

//Output
true
false

.join()

  • The join method returns a new string by concatenating all of the elements in an array, separated by a specified separator.

  • The syntax is - array1.join(separator).

  • The join method takes in a separator (optional) - A string to separate each pair of adjacent elements of the array. By default, it is a comma ,.

  • join() does not change the original array.

let array9=['Madhav',"madhav sahi",9,22,"Madhav Sahi",'Sahi','madhav',9,22];
let str=array9.join(',');
console.log(str);
console.log(str[6]);

//Output
Madhav,madhav sahi,9,22,Madhav Sahi,Sahi,madhav,9,22
,

.reverse()

  • The reverse method returns the array in reverse order.

  • The syntax is - array1.reverse()

  • It modifies the original array.(mutator method)

let array9=['Madhav',"madhav sahi",9,22,'madhav',9,22];
let anss= array9.reverse();
console.log(array9);
console.log(anss);
// output
[ 22, 9, 'madhav', 22, 9, 'madhav sahi', 'Madhav' ]
[ 22, 9, 'madhav', 22, 9, 'madhav sahi', 'Madhav' ]

.fill()

  • The fill() method returns an array by filling all elements with a specified value.

  • This method does not return a new array. Instead of it modifies the array on which this method is applied(it is a mutator method).

  • The value can be used to fill the entire array or it can be used to fill a part of the array.

  • It has 3 parameters with syntax - array1.fill(value,start-index,last-index)

  • value: It defines the static value with which the array elements are to be replaced.

  • start: (Optional): It defines the starting index from where the array is to be filled with the static value. If this value is not defined the starting index is taken as 0. If the start is negative then the net start index is length+start.

  • end :(Optional): This argument defines the last index up to which the array is to be filled with the static value. That value is excluded. If this value is not defined then by default the length is taken as end value.

let array9=['Madhav',"madhav sahi",9,22,'madhav'];
array9.fill('hello',1,3);
console.log("Array 9: "+ array9);
//it will fill hello from index 1 to (3-1)2

let array10=['Madhav',"madhav sahi",9,22,'madhav'];
array10.fill('hello',1);
console.log("Array 10: "+ array10);
//it will fill hello from index 1 to end

let array11=['Madhav',"madhav sahi",9,22,'madhav'];
array11.fill('hello');
console.log("Array 11: "+ array11);
//it will fill hello from start to end

//Output
Array 9: Madhav,hello,hello,22,madhav
Array 10: Madhav,hello,hello,hello,hello
Array 11: hello,hello,hello,hello,hello

Iterating over an Array

  • To iterate over an array, we can use for loop or for of loop.

  • For OF loop:-

  • The for...of loop is used to iterate through the values of an iterable(array,strings,maps,sets).

  • Direct access of object is given without using index and without reassessing the original main array.

  • The for...of loop cannot be used to iterate over an object.

// array
const students = ['John', 'Sara', 'Jack'];

// using for...of
for ( let element of students ) 
{
    console.log(element);
}
//Outuput
John
Sara
Jack

Thank you for reading...See you soon !!