Arrays in JavaScript

Arrays in JavaScript

What is an Array?

Arrays are used to store multiple values in a single variable by using this data type we can perform various methods on the data. Arrays are the most used datatypes to store multiple values. We can perform various tasks on the arrays in the most efficient way.

Arrays in javascript are created using `[ ]`. This can store any type of data like strings, numbers and objects. We can also use nested arrays which are called multi-dimensional arrays or 2d arrays.

const arr = ['element1', 'element2', 'element3'];  // string elements
const arr1 = [2, 4, 6, 8, 10];                     //number elements
const arr2 = [{ 'name': 'stark' },{ 'name': 'scarlet' }];//object elements
const arr3 = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
    ];                                               //nested arrays

Accessing Elements of Arrays

To access the elements of the arrays we use indexing of each element which starts from 0 to the length of the array. The syntax for this is a variable name followed by the square bracket inside which the index number is given.

To get the length of the array we use the length method on the array which returns the length of the array.

const arr = ['element1', 'element2', 'element3'];
console.log(arr.length)  // prints 2
console.log(arr[0])  // prints element1
console.log(arr[1])  // prints element2
console.log(arr[2])  // prints element3

Array Methods

Array methods are provided by JavaScript to perform various actions on the arrays. These are

indexof() and lastIndexof()

indexof() is used to find the first occurrence index of the passed value in the method

lastIndexof() is used to find the last occurrence index of the passed value in the method

const arr = [
  "element1",
  "element2",
  "element2",
  "element2",
  "element3",
  "element4",
];
console.log(arr.indexOf('element2'))        // prints  1
console.log(arr.lastIndexOf('element2'))    // prints  3

push() and pop()

push() is used to add new elements to arrays

const arr = ["element1", "element2", "element3"];
arr.push('element4')
console.log(arr)  
//  prints [ 'element1', 'element2', 'element3', 'element4' ]

pop() will delete the last element of the arrays

const arr = ["element1", "element2", "element3", "element4"];
arr.pop()
console.log(arr)
// prints [ 'element1', 'element2', 'element3' ]

shift() and unshift()

shift() is used to remove the first index element of the array and shift all the remaining elements to 1 step before and return the removed element

unshift is used to add a new element at the beginning of the array

const arr = ["element1", "element2", "element3", "element4"];
console.log(arr.shift()) // prints element1
console.log(arr)         // prints [ 'element2', 'element3', 'element4' ]

console.log(arr.unshift('element5')) // prints 4
console.log(arr)   // [ 'element5', 'element2', 'element3', 'element4' ]

slice() and splice()

slice() is used to slice out the elements in the array this method takes indexes as the arguments it can take a maximum of two arguments to start and end indexes this method doesn't modify the original array rather creates a new array and returns it will new values of the array

splice() is used to add new items to the arrays this can take four arguments

const arr = ["element1", "element2", "element3", "element4"];
console.log(arr.slice(1,3))    // prints [ 'element2', 'element3' ]
console.log(arr) // prints [ 'element1', 'element2', 'element3', 'element4' ]

const arr1 = ["element1", "element2", "element3", "element4"];
arr1.splice(2, 0, 'element5','element6')
//  2 is the start
//  0 is the number of elements to be deleted 
//  remaining arguments are to be added into the new array 
console.log(arr1) 
//prints ['element1','element2','element5','element6','element3','element4']

sort() and reverse()

sort() this function is used to sort the array in alphabetical order this returns a sorted array

reverse() this function is used to reverse array elements this returns reversed array

const arr = ['apple', 'ball', 'cat', 'dog']
console.log(arr.reverse()); // prints [ 'dog', 'cat', 'ball', 'apple' ]
console.log(arr);           // prints [ 'dog', 'cat', 'ball', 'apple' ]
console.log(arr.sort());    // prints [ 'apple', 'ball', 'cat', 'dog' ]
console.log(arr);           // prints [ 'apple', 'ball', 'cat', 'dog' ]

split() and join()

split() this method is used to convert a given string into an array it takes the argument by which the string should be split to convert it into the array

join() this method is used to convert the given array into a string and it takes the argument by which the array elements should be joined as a string

const arr = "apple,ball,cat,dog";
const str = arr.split(',');
console.log(str);    //  [ 'apple', 'ball', 'cat', 'dog' ]

const arr1 = ["apple", "ball", "cat", "dog"];
const arr2 = arr1.join(',');
console.log(arr2)    //  apple,ball,cat,dog

map() and filter()

map() this method is used to traverse each element of the array and to modify it based on the function passed to map()

filter() this method is used to filter down the elements of the array based on certain conditions which are passed as the function to the method. If the element satisfies the condition then the element is added to the new array else it won't be added to the array

const arr = [2,4,6,8,10]
const arr1 = arr.map(a => a*a)
console.log(arr1)    // [ 4, 16, 36, 64, 100 ]

const arr2 = [1,2,3,4,5,6,7,8,9,10]
const arr3 = arr2.filter( a => a%2==0)
console.log(arr3)    //  [ 2, 4, 6, 8, 10 ]

Thanks for Reading...