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:
Cheers ☕️