The arrays are considered as the fundamental data structure in JavaScript which allows to store and manipulate collections of values.
There are various operations you can perform on arrays. Here are some common array operations in JavaScript:
Accessing Elements
Example
let arr = [1, 2, 3, 4];
let firstElement = arr[0]; // 1
Adding Elements
- Push() is used to add elements to the end of the array.
- Using Unshift() we can able to add elements to the beginning of the array.
Removing Elements
- Pop() is used to remove elements to the end of the array.
- Using shift() we can able to remove the first elements of the array.
Iterating Over Arrays
Use loops like for or forEach() to iterate over array elements.
Array Methods
JavaScript provides a variety of built-in array methods like map(), filter(), and reduce() for more advanced operations.
Slicing and Splicing
By using slice() we can able to create a copy of a portion of an array.
By using splice() we can able to add or remove elements at a specific index.
Finding Elements
By using indexOf() we can able to find the index of a specific element.
By Using includes(), we can able to check if an array includes a certain element.
Filtering and Mapping
- By using filter() we can able to create a new array with elements that satisfy a condition.
- By using map() to create a new array by applying a function to each element.
Examples for the above array operations are mentioned below.
let arr = [1, 2, 3, 4];
arr.push(5); // [1, 2, 3, 4, 5]
arr.unshift(0); // [0, 1, 2, 3, 4, 5]
arr.pop(); // [0, 1, 2, 3, 4]
arr.forEach(function(element) {
console.log(element);
});
let slicedArr = arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // Removes 2 elements starting from index 1
let index = arr.indexOf(3); // 2
let includesElement = arr.includes(3); // true
let filteredArr = arr.filter(function(element) {
return element > 2;
});
// filteredArr: [3, 4]
let mappedArr = arr.map(function(element) {
return element * 2;
});
// mappedArr: [2, 4, 6, 8]
JavaScript provides a rich set of array methods that you can leverage based on your specific needs as there are some of the basic operations commonly used.