DEV Community

Cover image for Understanding and Applying Array Methods in JavaScript
Martins Onuoha
Martins Onuoha

Posted on

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โ€™ } ];
Enter fullscreen mode Exit fullscreen mode

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) // ['๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”', '๐Ÿฐ']
Enter fullscreen mode Exit fullscreen mode

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) // ['๐Ÿถ' '๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”']
Enter fullscreen mode Exit fullscreen mode

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) // ['๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”']
Enter fullscreen mode Exit fullscreen mode

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) // ['๐Ÿ‘', '๐Ÿ”', '๐Ÿถ']
Enter fullscreen mode Exit fullscreen mode

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) // ['๐Ÿถ', '๐Ÿ”', '๐Ÿ‘', '๐Ÿฎ',]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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 = ['๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”'];
Enter fullscreen mode Exit fullscreen mode

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); // ['๐Ÿฐ', '๐Ÿฐ', '๐Ÿ”']
Enter fullscreen mode Exit fullscreen mode

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); // ['๐Ÿฎ', '๐Ÿฐ', '๐Ÿ‘', '๐Ÿ”']
Enter fullscreen mode Exit fullscreen mode

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); // [ '๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”', '๐Ÿฅฌ', '๐Ÿƒ', '๐ŸŒฑ' ]
Enter fullscreen mode Exit fullscreen mode

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' } ]
*/
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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); // ๐Ÿฎ๐Ÿฅฌ๐Ÿ‘๐Ÿฅฌ๐Ÿ”
Enter fullscreen mode Exit fullscreen mode

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); // [ '๐Ÿฎ' ]
Enter fullscreen mode Exit fullscreen mode

toString

This method returns the string representation of the array and its elements.

const farm = ['๐Ÿฎ', '๐Ÿ‘', '๐Ÿ”'];

const stringFarm = farm.toString();

console.log(stringFarm); // ๐Ÿฎ,๐Ÿ‘,๐Ÿ”
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
 */
Enter fullscreen mode Exit fullscreen mode

### 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' }
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

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:

GitHub logo MartinsOnuoha / javascript-array-methods

Mutator, Accessor and Iteration Groups.


Cheers โ˜•๏ธ

Top comments (0)