Array Methods in JavaScript🚀

Array Methods in JavaScript🚀

Let's learn array methods in JavaScript💻

What are arrays in JavaScript🚀

Arrays in js, or any other programming language, basically store a collection of multiple items under a single variable name.

Declaration of Arrays:

There are two in javaScript to declare an array.

Method 1:

// declaring an array of frameworks based on JavaScript using [].
const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];

Method 2:

// declaring an array of frameworks based on javascript using new keyword
const frameworks = new Array("React Js" , "Angular Js", "Vue Js", "Next Js");

Examples:

// empty array
const myarray = [];
// array of numbers
const numberArray = [ 2, 4, 6, 8, 10, 12];
// array of strings
const stringArray = [ 'eat', 'code', 'sleep' , 'repeat'];
// array with mixed data types
const newarray = ['work', 'exercise', 1, true, null];

You can also store arrays, functions and other objects inside an array. For example,

// complex array containing multiple items of different types
const complexArray = [
    {
        'B1': 'Sleeper',
        'B2': 'Third AC',
        'B3': 'Second AC',
        'B4': 'First AC'
    },
    [1, 2 ,3, 4, 5, 6],
    function func1(){
        console.log('This is an function inside a complex array.')
    },  
];

Accessing the array elements:

// Access the array elements
// Arrays are 0 indexed in most of the programming languages,
// the position of each elemnet is 0,1,2... 
// to access a particular index, we use the following format: arrayname[index]

console.table(complexArray[0]); // printing the object in table format
console.log(complexArray[1]); // printing the number array
complexArray[2](); //callling the function func1

The following is printed on console.

image.png

Now we have discussed the basics of arrays, let's talk about array methods.

Array length

// length is a property and not a method
const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
console.log(frameworks.length); // prints the length of array
// Output: 4

Array reverse()

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
console.log(frameworks.reverse()); // reverses the array

// Output: [ 'Next Js', 'Vue Js', 'Angular Js', 'React Js' ]

Array sort()

The sort() function sorts the array in ascending order by default.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
console.log(frameworks.sort()); // sots the array in ascending order

// Output: [ 'Angular Js', 'Next Js', 'React Js', 'Vue Js' ]

Array fill()

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

// array of strings
const stringArray = [ 'eat', 'code', 'sleep' , 'repeat'];
stringArray.fill("development") 

console.log(stringArray);

// Output: [ 'development', 'development', 'development', 'development' ]

Array join()

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

const stringArray = ['Lets', 'Build' , 'Some', 'Stuff', '#iwritecode'];
let message = stringArray.join(" ");
console.log(message);

// Output: Lets Build Some Stuff #iwritecode

Array toString()

The toString() method returns a string formed by the elements of the given array.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js", 1, true];
console.log(frameworks.toString());

// Output: React Js,Angular Js,Vue Js,Next Js,1,true

Array pop()

The pop() method removes the last element from an array and returns that element.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
frameworks.pop();
console.log(frameworks);

// Output: [ 'React Js', 'Angular Js', 'Vue Js' ]

Array shift()

The shift() method removes the first element from an array and returns that element.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
console.log(frameworks.shift());
console.log(frameworks);

// Output: React Js
// [ 'Angular Js', 'Vue Js', 'Next Js' ]

Array push()

The push() method adds zero or more elements to the end of the array.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
frameworks.push('Sanity');
console.log(frameworks);
frameworks.push('Firebase','AWS Amplify');
console.log(frameworks);

// Output: [ 'React Js', 'Angular Js', 'Vue Js', 'Next Js', 'Sanity' ]
// [
//   'React Js',
//   'Angular Js',
//   'Vue Js',
//   'Next Js',
//   'Sanity',
//   'Firebase',
//   'AWS Amplify'
// ]

Array unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
console.log(frameworks.unshift('Firebase'))
console.log(frameworks);

// Output:5
// [ 'Firebase', 'React Js', 'Angular Js', 'Vue Js', 'Next Js' ]

Array concat()

The concat() method returns a new array by merging two or more values/arrays.

const Numbers1 = [1, 2, 3, 4, 5];
const Numbers2 = [6, 7, 8, 9, 10];

let Numbers = Numbers1.concat(Numbers2);
console.log(Numbers);

// Output: [
//     1, 2, 3, 4,  5,
//     6, 7, 8, 9, 10
//   ]

Array splice()

The splice() method returns an array by changing (adding/removing) its elements in place.

const frameworks = ["React Js" , "Angular Js", "Vue Js", "Next Js"];
// array.splice(startIndex,number of elements to be deleted,values to be inserted)
const removedelement = frameworks.splice(1,1,"firebase");
console.log(removedelement);
console.log(frameworks);

// Output: [ 'Angular Js' ]
// [ 'React Js', 'firebase', 'Vue Js', 'Next Js' ]

Array lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified element in the array.

const numArray = ["LCO", "iNueron", "LCO", "FSJS", "Data Science"];
//gives last index where LCO was found
console.log(numArray.lastIndexOf("LCO")) 
// for elements with single frequencey, it gives the element's index
console.log(numArray.lastIndexOf("FSJS"))

// Output:
// 2
// 3

Array indexOf()

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

const numArray = ["LCO", "iNueron", "LCO", "FSJS", "Data Science"];
//gives first index where LCO was found
console.log(numArray.indexOf("LCO")) 
// for elements with single frequencey, it gives the element's index
console.log(numArray.indexOf("FSJS"))
// if element is not present, it gives -1
console.log(numArray.indexOf("Django"))

// Output: 
// 0
// 3
// -1

Array of()

The of() method creates a new Array instance from the given arguments.

const coursesArray = Array.of("LCO", "iNueron", "FSJS", "Data Science");
//creates an array with given elements and stores it in assigned variable
console.log(coursesArray)

// Output: [ 'LCO', 'iNueron', 'FSJS', 'Data Science' ]

Array slice()

The slice() method returns a shallow copy of a portion of an array into a new array object.

const coursesArray = ["LCO", "iNueron", "FSJS", "Data Science"];
// array.slice(startIndex(inclusive), endIndex(exclusive));
const newArray = coursesArray.slice(2,4);
// from start index to end of array
const newArray1 = coursesArray.slice(1);

console.log(newArray)
console.log(newArray1)

// Output: 
// [ 'FSJS', 'Data Science' ]
// [ 'iNueron', 'FSJS', 'Data Science' ]

Array copyWithin()

The copyWithin() method copies array elements from one position to another in the given array.

const coursesArray = ["LCO", "iNueron", "FSJS", "Data Science"];
// array.copyWithin(index at which value is to be copied, startIndex, endIndex)
coursesArray.copyWithin(1,3);
// takes value of index 3 and copies it to index 1
console.log(coursesArray)

// Output: 
// [ 'LCO', 'Data Science', 'FSJS', 'Data Science' ]

That were the most important array methods used in JavaScript Hope the article was helpful.

Don't forget to give it a thumbs up👍🏻