Understanding and Mastering Array Methods in JavaScript

Mutator, Accessor, and Iterator Groups.

ยท

9 min read

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

ย