Array in JavaScript and its Methods

Array in JavaScript and its Methods

Array

In JavaScript Array is an ordered collection of data. In Array, a single variable is used to store multiple values. In Array each item has an index, we can access the elements by using the index number associated with it. The indexing in arrays starts from 0.

let arr=[1,2,3,4,5]

1. Creating an Array

We can create an array in 2 ways:

1.1. Using Square Brackets

Syntax

let arr =[1,2,3,4,5]

1.2. Using the new Array() keyword

Syntax

let arr=new Array(1,2,3,4,5)

2. Accessing and Modifying an Element

Each element in an array has its index number associated with it so we can access any element we want by using the index number.

To Modify an array by using the index number.

Eg.

let arr=[1,2,3,4,5];
//Accessing an element in Array
console.log(arr[1]);
console.log(arr[4]);
// Output
2
4
//Modifying an array 
let arr1=[1,2,3,4,5];
arr1[2]=9;
console.log(arr1);
// Output
[1,2,9,4,5]

3. Length of an Array

We can easily find the length of an array by using the built-in length property.

Eg.

let arr=[1,2,3,4,5];
console.log(arr1.length);
// Output
5

Array Methods

1. at()

It is used to return an array element at the given index. It can accept negative index also.

Syntax

at(index)

Eg.

let arr=[1,2,3,4,5];
console.log(arr1.at(2));
// Output
3

2. concat()

It is used to join two or more arrays and return a new Array.

Syntax.

concat(val1)
concat(val1,val2,.....)

Eg.

let arr=[1,2,3,4,5];
let arr1=[6,7,8,9];
console.log(arr.concat(arr1)
//Output
[1,2,3,4,5,6,7,8,9]

3. copyWithin()

It is used to copy a part of an array. It modifies the original array also.

Syntax

copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)

Eg.

let arr=[1,2,3,4,5];
console.log(arr.copyWithin(0,2,4));
//Output
[3,4,3,4,5]

4. entries()

It is used to return a new Array iterator object that contains a key-value pair.

Syntax

entries()

Eg.

let arr = [1,2,3,4,5];
let itt1 = arr.entries();
console.log(itt1.next().value);
console.log(itt1.next().value);
//Output
[0, 1]
[1, 2]

5. every()

Every returns true only if all the elements in the array satisfy the testing function and false if any element does not match the test function.

Syntax

every((element) => { /* … */ })

Eg.

let arr = [10,20,30,40,50];
console.log(arr.every(el=>el>5));
console.log(arr.every(el=>el>15));
//Output
true
false

6. fill()

Used to fill an array with a value from a starting index (default 0) to the ending index (default arrray.length). It modifies the original array.

Syntax

fill(value)
fill(value, start)
fill(value, start, end)

Eg.

let arr = [1, 2, 3, 4,5];
console.log(arr.fill(0, 2, 4));
console.log(arr.fill(5, 1));
//Output
[1, 2, 0, 0, 5]
[1, 5, 5, 5, 5]

7. filter()

It returns a new Array which contains all the elements which are returned true by the filter method.

Syntax

filter((element) => { /* … */ })

Eg.

let arr = [10,20,30,40,50];

let filterdArr=arr.filter(el=>el>25);
console.log(filterdArr);

//Output
[30, 40, 50]

8.find()

It returns the value of first element which satisfies the testing function and if no element is found which satisfies the testing condition it returns undefined.

Syntax

find((element) => { /* … */ })

Eg.

let arr = [1,2,3,4,5];

let elementPresent = arr.find(element => element >3);

console.log(elementPresent);
//Output

4

9. findIndex()

It returns the index of the first element that satisfies the testing function. Returns -1 if no appropriate match is found.

Syntax

findIndex((element) => { /* … */ })

Eg.

let arr = [1,2,3,4,5];
let arrIndex = arr.findIndex(element => element >3);
let arrIndex1 = arr.findIndex(element => element >30);
console.log(arrIndex);
console.log(arrIndex1);
//Output
3
-1

10. findLast()

It performs the opposite of find(). It returns the value of the last element which satisfies the testing function and if no element is found that satisfies the testing condition it returns undefined.

findLast((element) => { /* … */ })

Eg.

let arr = [1,2,3,4,5];

let elementPresent = arr.findLast(element => element >3);

console.log(elementPresent);
//Output
5

11. findLastIndex()

It returns the index of the last element that satisfies the testing function Returns -1 if no appropriate match is found.

findLastIndex((element) => { /* … */ })

Eg.

let arr = [1,2,3,4,5];

let elementPresent = arr.findLastIndex(element => element >3);

console.log(elementPresent);

//Output
4

12. flat()

This creates a new Array with all subarrays concatenated into it upto a specified depth.

Syntax

flat()
flat(depth)

Eg.

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

13. flatMap()

It returns a new Array formed after applying a callback function to each element, and flattened the array by 1 level.

Syntax

flatMap((element) => { /* … */ })

Eg.

const arr = [1, 2, [3], [4, 5], 6, []];

const flatArr = arr.flatMap(num => num);

console.log(flatArr);
//Output
[1, 2, 3, 4, 5, 6]

14. forEach()

It is used to call a function for each element present in an array.

Syntax

forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })
const arr = [1,2,3,4,5,6];
arr.forEach(element => console.log(element*2));
//Output
2
4
6
8
12

15. includes()

Check whether an element is present in an array or not. Returns a Boolean value.

Syntax

includes(searchElement)
includes(searchElement, fromIndex)

Eg.

const arr = [1, 2, 3,4,5];

console.log(arr.includes(2));
console.log(arr.includes(20));
//Output
True
False

16.indexOf()

Returns the index of the first element at which the given element is present in an array. Returns -1 if the given element is not present.

Syntax

indexOf(searchElement)
indexOf(searchElement, fromIndex)

Eg.

const arr = [1, 2, 3,2,5];

console.log(arr.indexOf(2));
console.log(arr.indexOf(2,3));
//Output
1
3

17. join()

It returns a new string from an array. The new string can be separated by using a separator. By default, the string is comma separated.

Syntax

join()
join(separator)

Eg.

const arr = [1,2,3];
console.log(arr.join());
console.log(arr.join(''));
//Output
"1,2,3"
"123"

18. keys()

Returns a new Array iterator object containing the keys for each index in an array.

Syntax

keys()

Eg.

const arr = [5,6,7];
const iterator = arr.keys();

for (const key of iterator) {
  console.log(key);
}
//Output
0
1
2

19. lastIndexOf()

Returns the index of the last element at which the given element is present in an array. Returns -1 if the given element is not present.

Syntax

lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)

Eg.

const arr = [1, 2, 3,2,5];

console.log(arr.lastIndexOf(2));
console.log(arr.lastIndexOf(2,2));
//Output
3
1

20. map()

Returns a new Array after applying the given callback function to each element in an array. Does not modify the original array.

Syntax

map((element) => { /* … */ })
map((element, index) => { /* … */ })
map((element, index, array) => { /* … */ })

Eg.

const arr = [1, 2,3,4,5];
arr.map((x,ind) =>{
console.log(ind,x*2)
});
//Output
0 2
1 4
2 6
3 8
4 10

21. pop()

Removes the last element from an array and returns that element also.

Syntax

pop()

Eg.

const arr = [1,2,3,4,5];
console.log(arr.pop());
console.log(arr);
//Output
5
[1,2,3,4]

22. push()

Add one or more elements to the end of an Array. Returns the new length of the array.

Syntax

push(element0)
push(element0, element1)
push(element0, element1, /* … ,*/ elementN)

Eg.

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

23. reduce()

Returns a single value after applying a callback function on each element of the Array.

Syntax

reduce((accumulator, currentValue) => { /* … */ })
reduce((accumulator, currentValue, currentIndex) => { /* … */ })
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ })

reduce((accumulator, currentValue) => { /* … */ }, initialValue)
reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue)
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue)

Eg.

const arr = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = arr.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);
console.log(sumWithInitial);
//Output
10

24. reduceRight()

Returns a single value after applying a callback function on each element of the Array(right to left).

Syntax

reduceRight((accumulator, currentValue) => { /* … */ })
reduceRight((accumulator, currentValue, index) => { /* … */ })
reduceRight((accumulator, currentValue, index, array) => { /* … */ })
reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue)

Eg.

const arr = [[0, 1], [2, 3], [4, 5]];
const result = arr.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));
console.log(result);
//Output
[4, 5, 2, 3, 0, 1]

25. reverse()

Reverse the order of elements in an array. It changes the original Array.

Syntax

reverse()

Eg.

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

26. shift()

Removes the first element from an array and returns the element.

Syntax

shift()

Eg.

const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(firstElement)
console.log(arr)
//Output
1
[2,3]

27. slice()

Extract a section of an array, and returns a new Array. Does not modify the original array.

Syntax

slice()
slice(start)
slice(start, end)

Eg.

const arr = [1,2,3,4,5,6];

console.log(arr.slice(2));
console.log(arr.slice(2, 4));
console.log(arr.slice());
console.log(arr.slice(-2));
//Output
[3, 4, 5, 6]
[3, 4]
[1, 2, 3, 4, 5, 6]
[5, 6]

28. some()

Returns true if any element in the array satisfies the testing function and false if all the element does not match the test function.

Syntax

some((element) => { /* … */ })
some((element, index) => { /* … */ })
some((element, index, array) => { /* … */ })

Eg.

const array = [1, 2, 3, 4, 5];
const even = (el) => el % 2 === 0;
console.log(array.some(even));
//Output
true

29. sort()

Sorts the elements in an array and returns the array. Modifies the original array.

Syntax

sort()
sort((a, b) => { /* … */ } )

Eg.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
const arr = [5,2,3,8,4];
arr.sort();
console.log(arr);
const array1 = [5,20,3,8,4];
array1.sort((a,b)=>a-b);
console.log(array1);
//Output
["Dec", "Feb", "Jan", "March"]
[2,3,4,5,8]
[3,4,5,8,20]

30. splice()

Adds and/or removes elements from an array. Modifies the original array.

Syntax

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)

Eg.

const arr = [1,2,3,4,5,6];
arr.splice(1, 1,99);
console.log(arr);
//Output
[1, 99, 3, 4, 5, 6]

31. toString()

Returns a string representing the calling array and its elements.

Syntax

toString()

Eg.

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
//Output 
"1,2,a,1a"

32. unshift()

Add one or more elements to the start of an Array. Returns the new length of the array.

Syntax

unshift(element0)
unshift(element0, element1)
unshift(element0, element1, /* … ,*/ elementN)

Eg.

const array1 = [1, 2, 3];

console.log(arr.unshift(4, 5));
console.log(arr);
//Output
5
[4, 5, 1, 2, 3]

33. values()

Returns a new Array iterator object containing the values for each index in an array.

Syntax

values()

Eg.

const arr = ['a', 'b', 'c'];
const iterator = arr.values();

for (const value of iterator) {
  console.log(value);
}
//Output
"a"
"b"
"c"