Understanding and Mastering Array Methods in JavaScript
Mutator, Accessor, and Iterator Groups.
In JavaScript, an array is a special type of object that represents a list of elements, where each element can be of any data type, including strings, numbers, and even other objects.
const mixedTypes = [โIyiolaโ, โ๐ฎโ, โSandraโ, [1, 2, 3], { name: โJohnโ } ];
One of the key features of arrays in JavaScript is their ability to dynamically resize themselves as needed. This means that you can add or remove elements from an array at any time without having to worry about pre-allocating memory.
Arrays in JavaScript also come with several built-in methods and functions that make it easy to perform common operations on the array, such as adding or removing elements, sorting the elements, and iterating over the elements.
That said, letโs get into some of the Array Methods in JavaScript and their use case:
Array methods are grouped into three major types:
Mutator methods,
Iteration methods and
Accessor methods.
Mutator Methods:
These methods modify the array.
push
The push()
method in JavaScript is used to add one or more elements to the end of an array and return the new length of the array.
Here's an example usage of the push()
method:
const animals = ['๐', '๐', '๐ฐ']
animals.push('๐ฎ') // adds a cow to the end of the array
// ['๐', '๐', '๐ฐ', '๐ฎ']
unshift
The unshift()
method in JavaScript is used to add one or more elements to the beginning of an array and return the new length of the array.
Here's an example usage of the unshift()
method:
const animals = ['๐', '๐', '๐ฐ'];
animals.unshift('๐ฎ'); // add a cow to the begining of the array
// ['๐ฎ', '๐', '๐', '๐ฐ']
pop
The pop()
method in JavaScript is used to remove the last element from an array and return that element, It follows the LIFO (Last In First Out) method:
Here's an example usage of the pop()
method:
const animals = ['๐', '๐', '๐ฐ']
animals.push('๐ฎ')
console.log(animals) // ['๐', '๐', '๐ฐ', '๐ฎ']
animals.pop()
console.log(animals) // ['๐', '๐', '๐ฐ']
shift
The shift()
method in JavaScript is used to remove the first element from an array and return that element, (FIFO method).
Here's an example usage of the shift()
method:
const animals = ['๐', '๐', '๐ฐ', '๐ฎ']
animals.shift()
console.log(animals) // ['๐', '๐ฐ', '๐ฎ']
reverse
The reverse()
method in JavaScript is used to reverse the order of the elements in an array. The first element becomes the last and the last element becomes the first, This method accepts no argument
Here's an example usage of the reverse()
method:
const animals = ['๐', '๐', '๐ฐ', '๐ฎ']
animals.reverse()
console.log(animals) // ['๐ฎ', '๐ฐ', '๐', '๐']
sort
The sort()
method in JavaScript is used to sort the elements in an array in place and return the sorted array, In the example below, using the sort method on the array arranges the elements in alphabetical order.
Here's an example usage of the sort()
method:
const numbers = [99, 3, 5, 1, 83, 75]
numbers.sort()
console.log(numbers) // [1, 3, 5, 75, 83, 99]
fill
The fill()
method in JavaScript is used to fill all the elements of an array with a static value. It modifies the original array in place and returns the modified array not including the end index. Hereโs an analogy, Given the barn variable:
Here's an example usage of the fill()
method:
const animals = ['๐', '๐', '๐ฐ'];
If we ran out of cows and chicken and decide to rare rabbits in their place, we would need to fill up that space in the barn that was formerly occupied by cows and chicken with just rabbits.
arr.fill(value, start, end)
const animals = ['๐', '๐', '๐ฐ'];
animals.fill('๐ฎ', 0, 2)
// from first index (0) to third index (2) not include
console.log(animals) // ['๐ฎ', '๐ฎ', '๐ฐ']
splice
The splice method inserts an element into an array at a specific index. It takes 3 arguments. The first argument (start) is the position (index) to start the insertion of the element, and the second argument (deleteCount) is the number of elements to replace/delete from the start index. If set to 0, no element is removed or deleted, the new element is just inserted into the specified position.
Here's an example usage of the splice()
method:
const animals = ['๐', '๐', '๐ฐ'];
// insert cow at index 1 (2nd position)
animals.splice(1, 0 '๐ฎ') ;
console.log(animals) // ['๐', '๐ฎ', '๐', '๐ฐ']
const animals = ['๐', '๐', '๐ฐ'];
animals.splice(1, 1 '๐ฎ') ;
console.log(animals) // ['๐', '๐ฎ', '๐ฐ']
Accessor Methods:
These methods do not modify the original /existing array but return a new modified array based on the original array.
concat
The concat()
method in JavaScript is used to merge two or more arrays and return a new array. It does not modify the original arrays.
Here's an example usage of the concat()
method:
const animals = ['๐', '๐', '๐ฐ'];
const fruit = ['๐', '๐ฅญ'];
const animalsAndFruit = animals.concat(fruit);
console.log(animalsAndFruit) // ['๐', '๐', '๐ฐ', '๐', '๐ฅญ']
filter
The filter()
method takes a function as an argument, the provided function acts as the condition against which each element is tested. A new array is created containing only elements that pass the test.
Here's an example usage of the filter()
method:
const farm = [
{ name: 'goat', type: 'animal', avatar: '๐' },
{ name: 'chicken', type: 'animal', avatar: '๐' },
{ name: 'rabbit', type: 'animal', avatar: '๐ฐ' },
{ name: 'cow', type: 'animal', avatar: '๐ฎ' },
{ name: 'lemon', type: 'fruit', avatar: '๐' },
{ name: 'mango', type: 'fruit', avatar: '๐ฅญ' },
];
const fruitsOnly = farm.filter(item => item.type === 'fruit')
console.log(fruitsOnly)
/*
[{ name: 'lemon', type: 'fruit', avatar: '๐' },
{ name: 'mango', type: 'fruit', avatar: '๐ฅญ' }]
*/
includes
This method checks whether an array includes a certain value among its elements. It returns true if a value is found and returns false if no matching element is found.
Here's an example usage of the includes()
method:
const animals = ['๐', '๐', '๐ฐ'];
const animalsHasMango = animals.includes('๐ฅญ')
const animalsHasChicken = animals.includes('๐')
console.log(animalsHasMango) // false
console.log(animalsHasChicken) // true
indexOf
The indexOf()
method in JavaScript returns the first index at which a given element can be found in an array, or -1 if it is not present.
Here's an example usage of the indexOf()
method:
const animals = ['๐ฎ', '๐', '๐', '๐ฐ'];
const indexOfCow = animals.indexOf('๐ฎ')
const indexOfRabbit = animals.indexOf('๐ฐ')
const indexOfMango = animals.indexOf('๐ฅญ')
console.log(indexOfCow) // 0
console.log(indexOfRabbit) // 3
console.log(indexOfMango) // -1
join
The join()
method creates and returns a new string by concatenating all of the elements of an array into one separated by commas. The elements can also be separated by any separator of your choice (instead of commas), just by passing in an optional argument.
Here's an example usage of the join()
method:
const animals = ['๐ฎ', '๐', '๐', '๐ฐ'];
const oneGroup = animals.join();
const fruit = animals.join('๐');
console.log(oneGroup) // ๐ฎ,๐,๐,๐ฐ
console.log(fruit) // ๐ฎ๐๐๐๐๐๐ฐ
slice
The slice()
method returns a shallow copy of a portion of the original array. Where the copy only contains elements within the specified start and end indices (end not included). The slice method accepts two optional arguments, the start index and the end index. If no argument is provided, a shallow copy of the array is returned.
Here's an example usage of the slice()
method:
const animals = ['๐ฎ', '๐', '๐', '๐ฐ'];
const copyAnimals = animals.slice();
const noCow = animals.slice(1);
const onlyCows = animals.slice(0, 1);
console.log(copyAnimals) // ["๐ฎ","๐","๐","๐ฐ"]
console.log(noCow) // ["๐","๐","๐ฐ"]
console.log(onlyCows) // ["๐ฎ"]
toString
The toString()
method in JavaScript returns a string representing the specified array and its elements.
Here's an example usage of the toString()
method:
const animals = ['๐ฎ', '๐', '๐', '๐ฐ'];
const stringAnimals = animals.toString();
console.log(stringAnimals) // ๐ฎ, ๐, ๐, ๐ฐ
Iteration Methods
Iteration methods are used to traverse an Array and access elements of that array dynamically.
every
The every()
method in JavaScript tests whether all elements in an array pass a specified test (function). The method returns true
if all elements pass the test; otherwise, it returns false
.
Here's an example usage of the every()
method:
const farm = [
{ name: 'goat', type: 'animal', avatar: '๐' },
{ name: 'chicken', type: 'animal', avatar: '๐' },
{ name: 'rabbit', type: 'animal', avatar: '๐ฐ' },
{ name: 'cow', type: 'animal', avatar: '๐ฎ' },
{ name: 'lemon', type: 'fruit', avatar: '๐' },
{ name: 'mango', type: 'fruit', avatar: '๐ฅญ' },
];
const farmHasOnlyAnimals = farm.every(item => item.type === 'fruit')
console.log(farmHasOnlyAnimals) // false
forEach
The forEach()
method is used to loop over elements of an array, it takes in a callback function as an argument, which in turn accepts 3 params (item, index, array).
Here's an example usage of the forEach()
method:
โitemโ is the current element in the iteration.
โindexโ is the position of the current element in the iteration.
โarrayโ is the array being traversed
const farm = [
{ name: 'goat', type: 'animal', avatar: '๐' },
{ name: 'chicken', type: 'animal', avatar: '๐' },
{ name: 'rabbit', type: 'animal', avatar: '๐ฐ' },
{ name: 'cow', type: 'animal', avatar: '๐ฎ' },
];
farm.forEach((item, index) => {
console.log(`${index + 1}. ${item.name}`)
});
/*
1. goat
2. chicken
3. rabbit
4. cow
*/
find
The find()
method in JavaScript returns the value of the first element in an array that satisfies a provided testing function. If no element satisfies the testing function, undefined
is returned.
Here's an example usage of the find()
method:
const farm = [
{ name: 'goat', type: 'animal', avatar: '๐' },
{ name: 'chicken', type: 'animal', avatar: '๐' },
{ name: 'rabbit', type: 'animal', avatar: '๐ฐ' },
{ name: 'cow', type: 'animal', avatar: '๐ฎ' },
];
const findRabbit = farm.find(item => item.avatar === '๐ฐ');
console.log(findRabbit) // { name: 'rabbit', type: 'animal', avatar: '๐ฐ' }
map
The map()
method takes a callback function as an argument and returns a new array containing the result from calling the callback function on each element of the original array.
Here's an example usage of the map()
method:
const animals = ['๐', '๐', '๐ฐ', '๐ฎ'];
const farm = animals.map(item => `${item}s`);
console.log(farm) // ['๐', '๐', '๐ฐ', '๐ฎ']
These are most of the common Array methods in JavaScript, most of them you can use in practical terms, and others you can use together to perform complex data manipulation on JavaScript array objects.
I hope my article was helpful to you. ๐
In my next article, we will be learning about JavaScript Getter
and Setter
stay tuned and also do not forget to check out my other articles