Array and its predefined functions in JAVASCRIPT

Array and its predefined functions in JAVASCRIPT

·

4 min read

What is Array?

In Javascript, an array is a built-in global object that allows you to simultaneously store multiple elements of different types. The size of an array is resizable and you can access the index using nonnegative integers.

Declaration of Array

const address = ["Gaya","Bihar",823001]; //Array Declaration
console.log(address)

Functions in array

Javascript gives us tons of methods to play around with an array.
Some of them are length ,join(), slice(), indexOf() ,concat() ,copyWithin() ,every() ,filter() ,flat() ,flatMap() ,indexOf() ,lastIndexOf() ,map()

push() - This function is used to add an element at the end of the array

const students = ["Ankush","mohan","anuraj"];
students.push("Alok","Prashant","Ankit","Sohan","VIpin"); //Adding elements in array at the end and return new length
console.log(students)

Merging two arrays using the push() method

const teachers = ["Hitesh","krishna","anurag"]
//Making them students   Hm.....
students.push(teachers);
console.log(students);
//Expected output
//["Ankush","mohan","anuraj","Alok","Prashant","Ankit","Sohan","VIpin","Hitesh","krishna","anurag"]

pop() -This function is used to remove the last element from the array and it returns the popped element and also reduces the length of the array.

Syntax:
Array.pop()

const favStates = ["Bihar","Chandigarh","kashmir"]
console.log(favStates.pop())
//Output: kashmir

length() -This function is used to find the length of the array

const students = ["Ankush","mohan","anuraj","Alok","Prashant","Ankit","Sohan","VIpin","Hitesh","krishna","anurag"];
console.log(students.length)
//Output - 11

Keys() - The array is all about playing with indexes to access the element so, keys are the function to see the index of the array

Syntax:

Object.keys(nameOfArray)

const favStates = ["Bihar","Chandigarh","kashmir"]
console.log(Object.keys(favStates));
//Output
//['0','1','2']

concat() - This function merges two arrays into one new array

//Syntax
// newArray = array1.concat(array2)
const oldFavStates = ["Bihar","Chandigarh","kashmir"];
const newFavStates = ["Rajasthan","Punjab"]
const favStates = oldFavStates.concat(newFavStates);

//Output
/*
['Bihar', 'Chandigarh', 'kashmir', 'Rajasthan', 'Punjab']
0:"Bihar"
1:"Chandigarh"
2:"kashmir"
3:"Rajasthan"
4:"Punjab"
length:5
*/

every() - This method traverse through the array and checks every element that matches the given condition or not and returns a boolean value.

const isPassed = (currMarks) => currMarks>35;
const marks = [75,95,12,42,32,53,32];
console.log(marks.every(isPassed))

// expected output: false

Slice() -This method returns the new array object with the given start index and end index.

Syntax:
Array.slice()
Array.slice(startIndex)
Array.slice(startIndex, EndIndex) note:- end index is excluded.

const favStates = ["Bihar","Chandigarh","kashmir","Rajasthan","Punjab"]
//indexes ------- [  '0'  ,  '1'       ,   '2'   ,   '3'      ,  '4'  ]
console.log(favStates.slice(1,4))
/*
Expected output:
(3) ['Chandigarh', 'kashmir', 'Rajasthan']
*/
console.log(favStates.slice(2)) // it will return all elements fron index '2'
/*
Expected output:
(3) ['kashmir', 'Rajasthan', 'Punjab']
*/

splice() -This method is used to modify (replace, remove) and add new elements to the existing array.

Syntax:
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, elementsToBeInserted)

const days= ["Sunday","Monday","Thrusday","Friday","Saturday"];
//indexes --[   '0'  ,  '1'   ,   '2'   ,    '3'   ,  '4'    ]
days.splice(2, 0, "Tuesday","Wednesday");
console.log(days)
/*
Output:
(7) ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday']
*/

fill() -This method is used to change the value in the array and return the modified array.

The difference between splice and fill is splice can add a new element but fill can only change the existing value from the given start index and end index.

Syntax:
Array.fill(value)
Array.fill(value, start)
Array.fill(value, start, end)

const days= ['Sunday', 'Monday', 'Monday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday'];
days.fill("Tuesday",2);
console.log(days)
/*
Output:
(7) ['Sunday', 'Monday', 'Tuesday', 'Tuesday', 'Tuesday', 'Tuesday', 'Tuesday']
Note: Here all value will changed with given value with the given start index

Includes() - This method traverse through the array and checks given element is present or not and returns a boolean value.

Syntax:
Array.includes(searchElement)
Array.includes(searchElement, fromIndex)

const favStates = ["Bihar","Chandigarh","kashmir","Punjab"]
console.log(favStates.includes("Bihar"));
//Output: true
console.log(favStates.includes("Bihar",2)); // checks from index 2
//Output: false

indexof() -This method traverses through the array and checks given element is present or not and returns the first index number of that element

if the element is not present then it returns -1

syntax:
Array.indexOf(searchElement)
Array.indexOf(searchElement, fromIndex)

const vehicle = ["Thar","Fortuner","XUV700","Scorpio","Audi Q3"]
console.log(vehicle.indexOf("XUV700"))
// Output: 2

join() - This method concatenates arrays elements into string format with a specified separator (by default comma ",") and returns a new string.

Syntax:
Array.join()
Array.join(separator)

const vehicle = ["Thar","Fortuner","XUV700","Scorpio","Audi Q3"]
console.log(vehicle.join())
//output: Thar,Fortuner,XUV700,Scorpio,Audi Q3
console.log(vehicle.join('-'))
//Output: Thar-Fortuner-XUV700-Scorpio-Audi Q3

filter() -This method creates a copy of the array with the filtered element(given condition by the user)

Syntax:

filter(function (element) { /* … */ })

const marks = [65,74,85,75,32,45,96,45,67];
const highestMarks = marks.filter(mark => mark>80)
console.log(highestMarks)
//Output: [85, 96]

conclusion

Arrays are a fundamental data structure in JavaScript and offer a wide range of methods for manipulating and working with data. Some of the most commonly used array methods include push and pop for adding and removing items from the end of an array, slice and splice for extracting and replacing items from within an array, and map, filter, and reduce for transforming and aggregating the items in an array. These methods, along with the many other array methods available in JavaScript, provide a powerful set of tools for working with and manipulating data in your code.