Understanding and Applying Array Methods in JavaScript
In JavaScript, Arrays are list-like objects whose prototype has functions and methods to perform bulk operations, mutations, and traversals. Arrays in JavaScript are dynamic and can contain a collection of elements of mixed types, including strings, numbers, and objects:
const mixedTypes = [โMartinsโ, โ๐ฎโ, โSamโ, [1, 2, 3], { name: โDavidโ } ];
Arrays in JavaScript only use numbers as an element index. One thing to note about Arrays in JavaScript is that; they arenโt dense data structures because the length of the array can be changed at any time. Also, data can be stored at non-contiguous locations in the array, as opposed to statically typed languages where the length and element type is defined on initialization.
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 Array push method in JavaScript appends a specified element to the end of the array. It takes one parameter, and the argument passed is then added to the end of the array:
const barn = ['๐ฎ', '๐', '๐'];
barn.push('๐ฐ')
console.log(barn) // ['๐ฎ', '๐', '๐', '๐ฐ']
unshift
Unlike the push method, the unshift Array method is used to add an element to the beginning of an array. It takes one parameter as well โ The element to insert at the start of the array:
const barn = ['๐ฎ', '๐', '๐'];
barn.unshift('๐ถ')
console.log(barn) // ['๐ถ' '๐ฎ', '๐', '๐']
pop
Sometimes we decide to remove the most recently added element from the end of an array. The pop Array method removes the last element in an array. It follows the LIFO (Last In, First Out) method:
const barn = ['๐ฎ', '๐', '๐', '๐ถ'];
barn.pop();
console.log(barn) // ['๐ฎ', '๐', '๐']
shift
We can equally remove elements from the beginning of an array (FIFO method). The shift array method takes no argument and removes the first element in the array.
const barn = ['๐ฎ', '๐', '๐', '๐ถ'];
barn.shift();
console.log(barn) // ['๐', '๐', '๐ถ']
reverse
Reverses the order of the elements of an array in place (First becomes the last, last becomes first). This method accepts no argument.
const barn = ['๐ฎ', '๐', '๐', '๐ถ'];
barn.reverse();
console.log(barn) // ['๐ถ', '๐', '๐', '๐ฎ',]
copyWithin
The copyWithin array method does a shallow copy of array elements at a specified index into another specific index. The copied values replace the values previously existing in that location. To understand this:
Given an array of numbers [1, 2, 3, 4, 5], Element 1 is at index 0. Element 4 is at index 3. If we call the copyWithin(โฆ) function on the array to replace the element at index 0 with the element at index 3, we will get [4, 2, 3, 4, 5].
const alpha = ['a', 'b', 'c', 'd', 'e'];
console.log(alpha.copyWithin(0, 3, 4)); // ["d", "b", "c", "d", "e"]
// copy to index 1 all elements from index 3 to the end
console.log(alpha.copyWithin(1, 3)); // ["d", "d", "e", "d", "e"]
fill
The fill method changes all elements in an array with a specified value from one specific index to another, not including the end index. Hereโs an analogy, Given the barn variable:
const barn = ['๐ฎ', '๐', '๐'];
If we ran out of cows and sheep and decided to rare rabbits in their place, we would need to fill up that space in the barn that cows and sheep formerly occupied with just rabbits.
arr.fill(value, start, end)
const barn = ['๐ฎ', '๐', '๐'];
barn.fill('๐ฐ', 0, 2); // from first index (0) to third index (2) not included
console.log(barn); // ['๐ฐ', '๐ฐ', '๐']
splice
The splice method inserts an element into an array at a specific index. It takes three 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.
const barn = ['๐ฎ', '๐', '๐'];
// insert rabbit at index 1 (2nd position)
barn.splice(1, 0, '๐ฐ');
console.log(barn); // ['๐ฎ', '๐ฐ', '๐', '๐']
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 is used to join/merge two or more arrays into one.
const barn = ['๐ฎ', '๐', '๐'];
const feed = ['๐ฅฌ', '๐', '๐ฑ'];
const barnAndFeed = barn.concat(feed);
console.log(barnAndFeed); // [ '๐ฎ', '๐', '๐', '๐ฅฌ', '๐', '๐ฑ' ]
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.
const farm = [
{ name: 'cow', avatar: '๐ฎ', type: 'animal'},
{ name: 'sheep', avatar: '๐', type: 'animal'},
{ name: 'hen', avatar: '๐', type: 'animal'},
{ name: 'lettuce', avatar: '๐ฅฌ', type: 'plant'},
{ name: 'mushroom', avatar: '๐', type: 'plant'}
];
const plantsOnly = farm.filter(element => element.type === 'plant');
console.log(plantsOnly);
/*
[ { name: 'lettuce', avatar: '๐ฅฌ', type: 'plant' },
{ name: 'mushroom', avatar: '๐', type: 'plant' } ]
*/
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.
const farm = ['๐ฎ', '๐', '๐'];
const farmHasChicken = farm.includes('๐');
const farmHasRabbit = farm.includes('๐ฐ');
console.log(farmHasChicken); // true
console.log(farmHasRabbit); // false
indexOf
This method returns the first index at which a given element is found in any given array. This method returns -1 if no element is found.
const farm = ['๐ฎ', '๐', '๐'];
const whereIsCow = farm.indexOf('๐');
const whereIsRabbit = farm.indexOf('๐ฐ');
console.log(whereIsCow); // 2
console.log(whereIsRabbit); // -1
join
The Array 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.
const farm = ['๐ฎ', '๐', '๐'];
const oneFamily = farm.join();
const withLettuce = farm.join('๐ฅฌ');
console.log(oneFamily); // ๐ฎ,๐,๐
console.log(withLettuce); // ๐ฎ๐ฅฌ๐๐ฅฌ๐
slice
The Array.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 and end indexes. A shallow copy of the array is returned if no argument is provided.
const farm = ['๐ฎ', '๐', '๐'];
const stringFarm = farm.toString();
const noCows = farm.slice(1);
const onlyCows = farm.slice(0, 1);
console.log(copyFarm); // [ '๐ฎ', '๐', '๐' ]
console.log(noCows); // [ '๐', '๐' ]
console.log(onlyCows); // [ '๐ฎ' ]
toString
This method returns the string representation of the array and its elements.
const farm = ['๐ฎ', '๐', '๐'];
const stringFarm = farm.toString();
console.log(stringFarm); // ๐ฎ,๐,๐
Iteration Methods
Iteration methods are used to traverse an Array and dynamically access elements of that array.
every
The every()
method tests whether all elements in the array pass the test implemented by the provided callback function. It returns a Boolean value (True/False).
const farm = [
{ name: 'cow', avatar: '๐ฎ', type: 'animal'},
{ name: 'sheep', avatar: '๐', type: 'animal'},
{ name: 'hen', avatar: '๐', type: 'animal'},
{ name: 'lettuce', avatar: '๐ฅฌ', type: 'plant'},
{ name: 'mushroom', avatar: '๐', type: 'plant'}
];
const farmHasOnlyAnimals = farm.every(element => element.type === 'animal');
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 three params (item, index, array).
โ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: 'cow', avatar: '๐ฎ', type: 'animal'},
{ name: 'sheep', avatar: '๐', type: 'animal'},
{ name: 'hen', avatar: '๐', type: 'animal'},
{ name: 'lettuce', avatar: '๐ฅฌ', type: 'plant'},
{ name: 'mushroom', avatar: '๐', type: 'plant'}
];
farm.forEach((item, index) => {
console.log(`${index + 1}. ${item.name}`)
});
/**
1. cow โโโโ
2. sheep
3. hen
4. lettuce
5. mushroom
*/
find
The find()
method returns the value of the first element in the provided array that satisfies the provided testing function. It takes in a callback function as an argument.
const farm = [
{ name: 'cow', avatar: '๐ฎ', type: 'animal'},
{ name: 'sheep', avatar: '๐', type: 'animal'},
{ name: 'hen', avatar: '๐', type: 'animal'},
{ name: 'lettuce', avatar: '๐ฅฌ', type: 'plant'},
{ name: 'mushroom', avatar: '๐', type: 'plant'}
];
const findCow = farm.find(element => element.avatar === '๐ฎ');
console.log(findCow); // { name: 'cow', avatar: '๐ฎ', type: 'animal' }
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.
const farm = ['๐ฎ', '๐', '๐'];
const plural = farm.map(element => `${element}s`);
console.log(plural); // [ '๐ฎs', '๐s', '๐s' ]
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.
You can find all the examples used here: https://github.com/MartinsOnuoha/javascript-array-methods
Cheers โ๏ธ