Array is one of the most important and frequently used concepts in JS. If someone raises the question “What is an array?”, we used to say,
“An array is a homogeneous collection of elements”.
My own definition of the array is,
It is a data structure used for arranging the elements or data as a group and each element can be accessed through its index.
To develop a JS enabled application, we should know this basic concept of arrays and the methods to be used.
sampleArray [ 0 ] – ‘HTML’
sampleArray [ 2 ] – ‘HTML’
Now, let us see some most commonly used array methods with simple examples
To find the length or size of a particular array.
Eg: console.log(sampleArray.length); Output: 3
- Adding an element to an array:
To add an element at the end of an array.
To add an element at the front of an array.
- Removing element(s) from an array:
To remove the last element from an array.
Here ES6 is removed as it was at the end of the array.
To remove the first element in the array.
Here HTML is removed as it was the first element in the array.
- Remove an item by index position – splice(pos,1)
To remove an element by index position.
Here ES6 is removed as it was present in the index 2 and the second parameter specifies the number of elements to be removed.
- Remove multiple items – splice(pos,n)
To remove more than one elements based on the index position.
Here n specifies the number of elements to be removed from the specific index pos.
- Copying an array:
To make a copy of an array with all its elements.
- Find the existence of an element:
To find whether an element present in an array or not.
Eg: var isPresent = sampleArray.includes(‘ES6’); // returns true var isPresent = sampleArray.includes(‘MongoDB’); // returns false
- Merging of arrays:
To combine/merge two or more arrays to form a new array.
Eg: var array1 = ['a', 'b', 'c']; var array2 = ['d', 'e', 'f']; console.log(array1.concat(array2)); Output: [ 'a', 'b', 'c', 'd', 'e', 'f' ];
- Operations/Functions that return a new array:
This returns a new array with the elements that pass the conditions given in the function.
Eg: const filteredArray = sampleArray.filter(element => element.length < 5); Output: [ ‘HTML’ , ‘ES6’ ] , Here the length of each element is less than 5.
Here, the given function is executed for each element of the array and the result will be pushed to a new array.
Eg: const sampleArray = [ 4, 2, 34, 50 ] const mappedArray = sampleArray.map(element => element*2); Output: [ 8 , 4 , 68 , 100 ]
- Looping through an array:
- for loop.
- for of
- for in
These are some of the methods which we can use to loop through an array.
And yes…We came to an end and I hope this blog on frequently used array methods will be useful to develop a js-based application. For more methods, refer the below link.