Arrays in Javascript...

Photo by Joan Gamell on Unsplash

Arrays in Javascript...

In this tutorial, we will learn about arrays in Javascript with the help of examples.

Arrays

An array is an object that can store multiple values at once. For example,

const words = ['Hitesh', 'Anurag', 'welcome'];

To Create an Array there are two ways:

1. Using an array literal

The easiest way to create an array is by using an array literal []. For example,

const array1 = ["eat", "sleep"];

2. Using the new keyword

You can also create an array using JavaScript's new keyword.

const array2 = new Array("eat", "sleep");

In above examples, we have created an array having two elements.

Here are more examples of arrays:

// empty array
const myList = [ ];
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'I', 'write', 'code'];
// array with mixed data types
const newData = ['I', 'write', 'code', 'Hitesh',1];

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

const newData = [
    {'Ineuron': 'Success'},
    [1, 2 ,3],
    function hello() { console.log('hello')}
];

Access Elements of an Array

You can access elements of an array using indices (0, 1, 2 …). For example,

const myArray = ['I','n','e','u','r','o','n'];

// first element
console.log(myArray[0]);  // "I"

// second element
console.log(myArray[1]); // "n"

Add an Element to an Array

You can use the built-in method push() and unshift() to add elements to an array.

The push() method adds an element at the end of the array. For example,

let dailyActivities = ['I', 'write','code'];

// add an element at the end
dailyActivities.push('repeat');

console.log(dailyActivities); //  ['I', 'write','code','repeat']

The unshift() method adds an element at the beginning of the array. For example,

let dailyActivities = ['I', 'write','code'];

//add an element at the start
dailyActivities.unshift('Success'); 

console.log(dailyActivities); // ['Success','I','write','code']

Change the Elements of an Array

You can also add elements or change the elements by accessing the index value.

let dailyActivities = ['I','write','code'];

// this will add the new element 'exercise' at the 2 index
dailyActivities[3] = 'Hitesh';

console.log(dailyActivities); // ['I','write','code','Hitesh']

Suppose, an array has two elements. If you try to add an element at index 3 (fourth element), the third element will be undefined. For example,

let dailyActivities = ['I','write','code'];

// this will add the new element 'exercise' at the 3 index
dailyActivities[4] = 'repeat';

console.log(dailyActivities); // ['I','write','code', undefined,'repeat']

Basically, if you try to add elements to high indices, the indices in between will have undefined value.

Remove an Element from an Array You can use the pop() method to remove the last element from an array. The pop() method also returns the returned value. For example,

let dailyActivities = ['I','write','code', 'repeat'];

// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['I','write','code']

// remove the last element from ['I','write','code', 'repeat']
const removedElement = dailyActivities.pop();

//get removed element
console.log(removedElement); // 'repeat'
console.log(dailyActivities);  // ['I','write','code']

If you need to remove the first element, you can use the shift() method. The shift() method removes the first element and also returns the removed element. For example,

let dailyActivities = ['I','write','code'];

// remove the first element
dailyActivities.shift();

console.log(dailyActivities); // ['write','code']

Array length

You can find the length of an element (the number of elements in an array) using the length property. For example,

const dailyActivities = [ 'I','write','code'];

// this gives the total number of elements in an array
console.log(dailyActivities.length); // 3

Array Methods

In JavaScript, there are various array methods available that makes it easier to perform useful calculations.

Some of the commonly used JavaScript array methods are: JavaScript Array Methods

1. map( )

This method creates a new array with the results of calling a provided function on every element in this array.

const arr = [1, 2, 3, 4, 5, 6];
const mapped arr.map (element = element + 30);
console. log (mapped);
//[31, 32, 33, 34, 35, 36]

2. filter( )

This method creates a new array with only elements that passes the condition inside the provided function.

const arr = [1, 2, 3, 4, 5, 61;
const filtered = arr. filter(element => element === 2 || element === 4);
console. log (filtered) ;
//[12, 4]

3. sort( )

This method is used to arrange/sort array’s elements either in ascending or descending order.

const arr = [1, 2, 3, 4, 5, 6];
const alphabet= ["f", "a", "c", "v", "z"];
//sort in descending order
descend= arr. sort ( (a, b) =>a>b?-1:1);
console.log(descend);
//[6, 5, 4, 3, 2, 11]

//sort in ascending order
ascend = alphabet. sort( (a, b) >a > b ? 1: -1);
console. log (ascend);
//["a", "c", "f", "v", "z"]

4. forEach( )

This method helps to loop over array by executing a provided callback function for each element in an array.

const arr = [1, 2, 3];
{
arr. forEach (element => {
console. log (element);
//1
//2
//3

5. concat( )

This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

const arr1 = ["a", "b", "c"];
const arr2 = ["d", "e", "f"l;
console. log (arr1. concat (arr2)) ; // "a", "b", "C", "d", "e", "f"]
console. log(arr1); //[ "a", "b", "c"]
console. log (arr2); // ["d", "e", "f"]

6. every( )

This method checks every element in the array that passes the condition, returning true or false as appropriate.

const arr = [1, 2, 3, 4, 5, 6, 71];
// all elements are greater than 5
const greaterFive = arr.every (num=>num> 5);
console. log (greaterFive) ; // false

// all elements are less than 9
const lessnine = arr.every (num => num< 9);
console. log ( lessnine) ; // true

7. some( )

This method checks if at least one element in the array that passes the condition, returning true or false as appropriate.

const arr = [1, 2, 3, 4, 5, 6, 71];
//at least one element is greater than 5?
const greaterNum = arr.some (num => num > 5);
console. log(greaterNum); // true
//at least one element is less than or equal to 0?
const lessNum = arr. some(num => num<= 0);
console. log (lessNum); // fa lse

8. includes( )

This method checks if an array includes the element that passes the condition, returning true or false as appropriate.

const arr = [1, 2, 3, 4, 5, 6] ;
console. log(arr. includes (2))); // true
console. log (arr. includes (7)); // false

9. join( )

This method returns a new string by concatenating all of the array’s elements separated by the specified separator.

const arr = ["m", "a", "n", "d", "e", "e", "p"];
console.. log (arr. join (" ")); // mandeep

10. reduce( )

This method applies a function against an accumulator and each element in the array to reduce it to a single value.

const arr = [1, 2, 3, 4, 5, 6];
const reduced = arr. reduce( (total, current) => total + current);
console. log ( reduced); // 21

11. find( )

This method returns the value of the first element in an array that pass the test in a testing function.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const found = arr. find (element => element > 5);
console. log (found) ; // 6

12. findIndex( )

This method returns the index of the first element in an array that pass the test in a testing function.

const arr = ["Danny", "Mandeep", "John", "Ruby"l;
const indexFinder = arr.findIndex (element => element === "Mandeep");
console. log(indexFinder);  // 1

13. indexOf( )

This method returns the index of the first occurrence of the specified element in the array, or -1 if it is not found.

const arr = ["Danny", "Mandeep", "John'", "Ruby"] :
const indexFinder = arr.indexof("Mandeep ");
console.log (indexFinder) ; // 1

14. fill( )

This method fills the elements in an array with a static value and returns the modified array.

const arr = new Array(3) ;
console. log(arr) ; // [empty, empty,empty]
console. log(arr.fill (10)) ; // [10, 10, 10]

15. slice( )

This method returns a new array with specified start to end elements.

const arr = ["a", "b", "c", "d", "e"];
const sliced = arr.slice (2, 4);
console. Log(sliced) ; // "c", "d"]
console. log (arr) ; //["a", "b", "c", "d", "e"]

16. reverse( )

This method reverses an array in place. Element at last index will be first and element at 0 index will be last.

const arr = [1, 2, 31;
arr. reverse () ;
console. log (arr) ; // [3, 2, 1]

17. push( )

This method adds one or more elements to the end of array and returns the new length of the array.

const fruits = ["Apple", "Peach"] ;
console. log (fruits. push ("Banana")); // 3
console. log(fruits); // ["Apple", "Peach", "Banana"]

18. pop( )

This method removes the last element from the end of array and returns that element.

const fruits = ["Apple", "Peach "l ;
fruits.pop ();
console. log (fruits); // ["Apple"]

19. shift( )

This method removes the first element from an array and returns that element.

const fruits = ["Apple", "Peach"] ;
fruits.shift () ;
console. log(fruits) ; // ("Peach"]

20. unshift( )

This method adds one or more elements to the beginning of an array and returns the new length of the array.

const fruits = ["Apple", "Peach" ] ;
console. log (fruits. unshift ("Banana" ) ) ; // 3
console. log (fruits) ; // ["Banana", "Apple", "Peach "]

Thankyou for your patience. Will soon meet for learning new Concept. Till then Keep learning, Keep exploring.

Did you find this article valuable?

Support Abhinav Jaiswal by becoming a sponsor. Any amount is appreciated!