Array and all its methods in Javascript

Array and all its methods in Javascript

The Array in Javascript helps store a collection of multiple items under a single variable name and has different methods to perform various operations.

How to initialize an array?

let name = ["Mike","Samuel","Robert"];

Different array methods in Js:

1. at() :

This method takes an integer value and returns the item at that index, works for positive and negative integers. Negative integers count back from the last item in the array.

let cars = ["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"];
let index = 2;
console.log(cars.at(index));

O/P: Jaguar

2. concat() :

This method is used to concatenate two arrays.

let foreigncar = ["bmw","jaguar","landrover","volswagen"];
let indiancar = ["marutisuzuki","tata","mahindra"]
mixedcar = foreigncar.concat(indiancar);
console.log(mixedcar);

O/P: [
  'bmw',
  'jaguar',
  'landrover',
  'volswagen',
  'marutisuzuki',
  'tata',
  'mahindra'
]

3.copywithin() :

method copies array elements to another position in the array, overwriting existing values. It returns the changed array

Syntax: array.copyWithin(target, start, end).

let numbers = [1,2,3,4,5,6,7,8];
numbers.copyWithin(4,0,3)
console.log(numbers);

O/P: [
  1, 2, 3, 4,
  1, 2, 3, 8
]

//first argument is the target index where data will be copied 
//second argument is starting index and third is ending index of the data chosen to copy.

4. entries() :

This method returns a new Array Iterator object that contains key/value pairs for each index in the array.


let array1 = ['a', 'b', 'c'];

let iterator1 = array1.entries();

for (let i=0; i<=2; i++){
console.log(iterator1.next().value);
}

O/P: [ 0, 'a' ]
     [ 1, 'b' ]
     [ 2, 'c' ]

5. every() :

This method executes a function for each array element. It returns true if the function returns true for all the array elements and false if it just returns false for one element. Note: It does not execute the function for an empty array.

let even = [2,4,6,40,10,80];

function checkeven(even) {
  return even%2==0;
}
console.log(even.every(checkeven));

O/P: True

6. fill() :

This method is used to fill values a certain value at the given index. It takes a value to fill and the start and end index and the end index is exclusive.

let cars = ["bmw","jaguar","landrover","volswagen"];
cars.fill("lexus",2,4)
console.log(cars);

O/P: [ 'bmw', 'jaguar', 'lexus', 'lexus' ]
//size of array remains the same it fills the data with the given argument

7 . filter() :

This method creates a new array with elements that pass the check provided by a function. Note: It does not execute the function for an empty array.

const array1 = [1, 30, 39, 29, 10, 13];
const result = array1.filter(array1 => array1 %2 ==0);

console.log(result);

O/P: [30,10]

8. find() :

This method finds the first element that passes a test provided by the function. If it find nothing then return undefined

let array = [5, 12, 8, 130, 44];
let found = array.find(element => element > 10);
console.log(found);

O/P: [12]

9. findIndex() :

This method returns the index of the first element in an array that satisfies the condition.

let cars = ["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"];

const isLargeNumber = (element) => element.length < 4;

console.log(cars.findIndex(isLargeNumber));

O/P: 1

10. findLast() :

This method returns the value of the first element(reverse order) in an array that satisfies the condition.

let cars = ["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"];

const isLargeNumber = (element) => element.length < 4;

console.log(cars.findLast(isLargeNumber));

O/P: bmw

11. findLastIndex() :

This method iterates the array in reverse order and returns the index of the first element that satisfies condition.

let cars = ["volswagen","bmw","jaguar","landrover"];

const isLargeNumber = (element) => element.length < 4;

console.log(cars.findLastIndex(isLargeNumber));

12. flat() :

This method is used to reduce the nesting of array. It takes depth as a parameter and flatten the array according to the depth provided.

By default depth is 1.

let cars = ["volswagen","bmw","jaguar","landrover",["Yamaha","Bajaj"]];

console.log(cars.flat()); //taking default value

let carss = ["volswagen","bmw","jaguar","landrover",[[["Yamaha","Bajaj"]]]];

console.log(carss.flat(2)); //remove two level of nesting 

O/P : [ 'volswagen', 'bmw', 'jaguar', 'landrover', 'Yamaha', 'Bajaj' ]
[ 'volswagen', 'bmw', 'jaguar', 'landrover', [ 'Yamaha', 'Bajaj' ] ]

13. flatMap() :

This method first maps the elements to a given condition and then it flattens the array. It is like first, we use the map function and then the flat function.

let numms = [1, 2, [3], [4], 6, []];
let flattened = (numms.flatMap(num => [num*2]));
console.log(flattened);

O/P: [2,4,6,8,12,0]

14. forEach() :

The forEach method calls a function for each element in the array.

let cars = ["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"];
cars.forEach(element => console.log(element));

O/P: volswagen
bmw
jaguar
landrover
volswagen
jaguar
landrover
volswagen

15. from() :

This method creates a new array instance from an iterable or array-like object.

console.log(Array.from("Volsvagen"));

O/P: ['V', 'o', 'l','s', 'v', 'a','g', 'e', 'n']

16. includes() :

checks if the item exists at a given index. It takes two arguments first is the item to check and the second is the given index to check. Returns boolean value

let cars = ["bmw","jaguar","landrover","volswagen"];
console.log(cars.includes("landrover",2));

O/P: [True]

console.log(cars.includes("landrover",1));

O/P: [False]

17. indexOf() :

It checks the index of a value given if there are multiple values exist then it will return the first occurrence.

let cars = ["bmw","jaguar","landrover","volswagen"];
console.log(cars.indexOf("landrover"));

O/P: [2]

18. isArray() :

This method returns if the given object is an array or not and returns a boolean value true or false accordingly.

let cars = ["bmw","jaguar","landrover","volswagen"];
console.log(Array.isArray(cars));

O/P: [True]

19. join() :

It joins the given character to the array and returns the string. it does not change the original array

let cars = ["bmw","jaguar","landrover","volswagen"];
c=cars.join(":");
console.log(c)
console.log( typeof c === 'string' );

O/P: [bmw:jaguar:landrover:volswagen]
     True

20. keys() :

This method returns a new array iterator object that contains the key of each index in the array.

 let numms = [ 5,6,7,8 ];          
// array.keys() method is called     
let iterator = numms.keys();          
// printing index array using the iterator     
for (let key of iterator) {         
console.log(key);     }

O/P: 
 0
 1
 2
 3

21. length :

it is used to find the length of the array

let car = ["bmw","tata","jaguar","landrover","volswagen"];
console.log(car.length);

O/P: 5

//When we dont know the length and wnt last element 

console.log(car[car.length-1]);
O/P: volswagen
// because the array index start with 0 and the above length is 5

22. lastIndexOf() :

It returns the last index of the given element, returns -1 if the value is not found, starts at a specified index and searches from right to left.

let cars = ["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"];
console.log(cars.lastIndexOf("volswagen"));

O/P: 7

23. map() :

creates a new array by calling a function for every array element. It does not change the original array.

const numbers = [1, 2, 3, 4];
const newArr = numbers.map(Function)
console.log(newArr)

function Function(num) {
  return num * 2;
}

O/P: [2,4,6,8]

24. of() :

This method creates a new array instance with variables present as the argument of the function.

Array.of(1, 2, 3, 4);
Array.of("volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen");
Array.of(2,3,4,'Hey','its','of','function')

O/P: [1,2,3,4]
["volswagen","bmw","jaguar","landrover","volswagen","jaguar","landrover","volswagen"]
[2,3,4,'Hey','its','of','function']

25. pop() :

It removes (pops) the last element from the array and returns it.

const numbers = [1, 2, 3, 4];
console.log(numbers.pop())
console.log(numbers)

O/P: 4
[ 1, 2, 3 ]

26. push() :

This method pushes a new element to the last position of the array.

let car = ["bmw","tata","jaguar","landrover","volswagen"];
car.push("skoda");
console.log(car);

O/P: [ 'bmw', 'tata', 'jaguar', 'landrover', 'volswagen', 'skoda' ]

27. reduce() :

This method reduces the value to a single value.

let arr1 = [1,2,3,4,5,6,7,8,9]
let newarr = arr1.reduce((a,b) =>{

        return a+b;
})

console.log(newarr);

O/P: 45

28. reduceRight() :

This method executes the reducer function for each array element. It works from right to left and returns a single value.

let arr1 = [1,2,3,4,5,6,7,8,9]
let newarr = arr1.reduceRight((a,b) =>{
         return a-b;
})
console.log(newarr);

O/P: -27

29. reverse() :

It reverses the order of the element in the array and overwrites the original array.

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

O/P: [ 4, 3, 2,1 ]

30. shift() :

it removes the first item in the array.

const numbers = [1, 2, 3, 4];
console.log(numbers.shift())
console.log(numbers)

O/P: 1
[ 2, 3, 4 ]

31. slice() :

This method returns a sliced array according to the start and end index provided. If only 1 value is provided then it will consider it as a start value and will consider the end value as -1 and go till the last element.

If a negative value is provided then it will start counting backward from the array

let car = ["bmw","tata","jaguar","landrover","volswagen"];
console.log(car.slice(1,3));
O/P: [ 'tata', 'jaguar' ]
// both values provided

let car = ["bmw","tata","jaguar","landrover","volswagen"];
console.log(car.slice(1));
O/P: [ 'tata', 'jaguar', 'landrover', 'volswagen' ]
// single value treated as starting value

let car = ["bmw","tata","jaguar","landrover","volswagen"];
console.log(car.slice(-2));
O/P: [ 'landrover', 'volswagen' ]
// in negative value it is starting from forward

32. some() :

checks whether even a single element passes the specified condition id yes return true otherwise false.

let nums = [1, 2, 3, 4, 5];
let checkeven = (element) => element % 2 === 0;
console.log(nums.some(checkeven));

O/P: True

33. sort() :

It sorts the elements in the array. for reverse sort we use(array.reverse(array.sort()));

let numbers = [1, 6, 3,9, 4,77,13];
numbers.sort()
console.log(numbers);

O/P:[
  1, 13, 3, 4,
  6, 77, 9
]
//taking 13 before 3 before it is cinsidering only the first value

34. splice() :

This method is used to insert the element at a given index. it takes 2 values, if the second value is 0 then it won't delete the value, otherwise, it deletes the value at the next index to the given index value.

let car = ["bmw","tata","jaguar","landrover","volswagen"];
car.splice(2,0,"skoda","mg");
console.log(car);

O/P: [ 'bmw', 'tata', 'skoda', 'mg', 'jaguar', 'landrover', 'volswagen' ]
//not remove any element because the 2nd argument is 0

let car = ["bmw","tata","jaguar","landrover","volswagen"];
car.splice(2,1,"skoda","mg");
console.log(car);

O/P: [ 'bmw', 'tata', 'skoda', 'mg', 'landrover' , 'volswagen' ]
//removed the jaguar  because the first argument is 2 and its next value in array index 2.

let car = ["bmw","tata","jaguar","landrover","volswagen"];
car.splice(2,1);
console.log(car);

O/P: [ 'bmw', 'tata', 'landrover', 'volswagen' ]
// if no value is provided to insert but second value is provided then the value after the first value is removed

35. toString() :

This method represents the array into a string. It does not change the original array.

let cars = ["volswagen","bmw","jaguar","landrover"];
console.log(cars.toString());
console.log(Array.isArray(cars));

O/P: volswagen,bmw,jaguar,landrover

36. Unshift() :

add new elements at the beginning of the array.

let numbers = [1,2,3,4];
numbers.unshift(7,9)
console.log(numbers);

O/P: [ 7, 9, 1, 2, 3, 4 ]

37. values() :

This method returns a new array iterator object that iterates the value of each index in the array.

let cars = ["volswagen","bmw","jaguar","landrover"];

const carrss = cars.values();

for (const value of carrss){
    console.log(value);
}

O/P: volswagen
bmw
jaguar
landrover