Array Methods in JavaScript
Array Methods in JavaScript To help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.v 1
Array Methods in JavaScript
To help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.v
1. JavaScript Array length
The length property of an array returns the number of elements in the array. It automatically updates as elements are added or removed. The length property can also be used to set the length of an array.
let a = ["HTML", "CSS", "JS", "React"];
console.log(a.length);
// to set the length of an array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length = 2;
2. JavaScript Array toString() Method
The toString() method converts the given value into the string with each element separated by commas. Every JavaScript object has a toString() method. The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.
let a = ["HTML", "CSS", "JS", "React"];
let s = a.toString();
console.log(s);
3. JavaScript Array join() Method
This join() method creates and returns a new string by concatenating all elements of an array. It uses a specified separator between each element in the resulting string. It behaves just like toString(), but in addition you can specify the separator.
let a = ["HTML", "CSS", "JS", "React"];
console.log(a.join('|'));
4.JavaScript Array at()
ES2022 introduced the array method at(). The at() method returns an indexed element from an array. The at() method returns the same as []. Many languages allow negative bracket indexing like [-1] to access elements from the end of an object / array / string. This is not possible in JavaScript, because [] is used for accessing both arrays and objects. obj[-1] refers to the value of key -1, not to the last property of the object. So to solve this the at() method was introduced in ES2022.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(-2);
5.JavaScript Array.pop() Method
The pop() method is used to remove elements from the end of an array. The pop() method returns the value that was "popped out". It changes the orginal array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
6.JavaScript Array push()
The push() method is used to add an element at the end of an Array. As arrays in JavaScript are mutable objects, we can easily add or remove elements from the Array. It changes the orginal array.
let a = [10, 20, 30, 40, 50];
a.push(60);
a.push(70, 80, 90);
console.log(a);
Shifting Elements
Shifting is equivalent to popping, but working on the first element instead of the last.
7.JavaScript Array shift()
The shift() method removes the first array element and "shifts" all other elements to a lower index. It used to remove elements from the beginning of an array. The shift() method returns the value that was "shifted out".
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift(); //[Orange, Apple, Mango]
8.JavaScript Array unshift()
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements. The unshift() method returns the new array length. It used to add elements to the front of an Array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
9.JavaScript Array delete Operator
The delete operator is used to delete the given value which can be an object, array, or anything. Using delete() leaves undefined holes in the array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
To delete object
let emp = {
firstName: "Riya",
lastName: "Kaur",
salary: 40000
}
console.log(delete emp.salary);
console.log(emp);
10.JavaScript Array concat() Method
The concat() method is used to concatenate two or more arrays and it gives the merged array. The concat() method creates a new array by merging (concatenating) existing arrays. The concat() method does not change the existing arrays. It always returns a new array. The concat() method can take any number of array arguments. The concat() method can also take strings as arguments:
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
11.JavaScript Array copyWithin()
The copyWithin() method copies array elements to another position in an array. The copyWithin() method overwrites the existing values. The copyWithin() method does not add items to the array. The copyWithin() method does not change the length of the array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
12.JavaScript Array flat()
The flat() method creates a new array with sub-array elements concatenated to a specified depth. The flat() method is used to flatten the array i.e. it merges all the given array and reduces all the nesting present in it.
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
13.JavaScript Array splice()
The splice() method can be used to add new items to an array. The splice() method returns an array with the deleted items.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
- The first parameter (2) defines the position where new elements should be added (spliced in).
- The second parameter (0) defines how many elements should be removed.
- The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
14.JavaScript Array slice()
The slice() method slices out a piece of an array into a new array. The slice() method creates a new array. The slice() method does not remove any elements from the source array.
const a = [1, 2, 3, 4, 5];
const res = a.slice(1, 4);
console.log(res);
console.log(a)
The slice() method creates a new array by extracting elements from index 1 to 3 (exclusive of 4) from the original array. The original array remains unchanged, and the result is [2, 3, 4].
15. JavaScript Array some() Method
The some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument function.
const a = [1, 2, 3, 4, 5];
let res = a.some((val) => val > 4);
console.log(res);
- The some() method checks if at least one element in the array satisfies the provided condition.
- (val) => val > 4: The condition checks if any element in the array is greater than 4.
- The method stops as soon as it finds the first matching element, making it efficient for large arrays.
16. JavaScript Array map() Method
The map() method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method.
let a = [4, 9, 16, 25];
let sub = a.map(geeks);
function geeks() {
return a.map(Math.sqrt);
}
console.log(sub);
- The code defines a geeks function, but instead of operating on the individual array 'a' elements, it applies Math.sqrt() to the entire a array, resulting in a nested array of square roots.
- The output will be an array of the same length as a, but each element will be the result of applying arr.map(Math.sqrt).
17. JavaScript Array filter() method
The filter() method in JavaScript creates a new array with all elements that pass the test implemented by the provided function. It does not modify the original array.
let a1 = [1, 2, 3, 4, 5]
let a2 = a1.filter((num) => num > 1)
console.log(a2)
- The filter() method is used to create a new array (a2) that contains all elements of the original array that satisfy the condition (num > 1).
- The filter() method does not modify the original array. It returns a new array, leaving the original one unchanged.
18. JavaScript Array reduce() Method
The reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
let a = [88, 50, 25, 10];
let sub = a.reduce(geeks);
function geeks(tot, num) {
return tot - num;
}
console.log(sub);
- The reduce() method iterates over the array 'a' and applies the geeks function, which subtracts each element (num) from the running total (tot).
- For the array [88, 50, 25, 10], the calculation proceeds as: 88 - 50 - 25 - 10.
19. JavaScript Array reverse() method
The reverse() method is used to reverse the order of elements in an array. It modifies the array in place and returns a reference to the same array with the reversed order. The reverse() method reverses the order of elements in the array arr in place, modifying the original array. After applying reverse(), the array.
let a = [1, 2, 3, 4, 5];
a.reverse();
console.log(a);
20. JavaScript Array values() method
The values() method returns a new Array Iterator object that contains the values for each index in the array.
const a = ["Apple", "Banana", "Cherry"];
const res = a.values();
for (const value of res) {
console.log(value);
}
- The values() method returns an iterator object that allows iterating over the values of the 'a' array.
- The for...of loop is used to iterate over the iterator and log each fruit ("Apple", "Banana", "Cherry") to the console.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.