A Dirty Quick Refresher On JavaScript Array Methods You Need To Know

by kleamerkuri
Refresher on JavaScript array methods.

Did you know you can use JavaScript array methods to create a new array without modifying the original one?

Arrays are the workhorses of JavaScript, providing a powerful way to store and manipulate collections of data.

It’s always good to have a solid understanding of the array methods that’ll keep your array skills sharp 🙃

In this blog post, we’ll take a quick and fun refresher on a few essential array methods like filter, map, and reduce.

We’ll explore how these methods can help you filter out unwanted elements, map and transform data, and reduce arrays to a single value with just a few lines of code.

Tip: It gets even better! You can chain array methods together to perform complex operations.

So, prepare for some array awesomeness that will level up your coding game in no time!

forEach

The JavaScript forEach() method is a newer option that can be used instead of a traditional for-loop.

forEach() calls a callback function once for each item in an array. The callback mutates the original array since forEach() returns undefined and cannot be chained to another method.

Example: forEach( (item) => { // do something } )

Above, the item parameter represents each element in the array. To access the index of the array element, pass a second parameter to the callback.

See it in action: How To Build An Easy Animated Hamburger Menu

map

Similarly to forEach, the map() method loops over an array, but it returns a new array of the results.

Example: let newArray = map( (item) => { // do something } )

map() is good for transforming elements in an array, generating a new array out of them.

Tip: Remember to return a value within the callback function or you’ll get undefined!

find

The find method iterates over each element in an array applying a callback function.

find returns the first match or undefined.

Example: Find the first occurring negative number in the list.

const myList = [10, -20, 50, -70, 80];

const negativeNum = myList.find( el => el < 0 );
console.log(negativeNum) // Result: -20

findIndex

Very similar to find, findIndex returns the index of the first element that’s a match.

If no match is found, the return value is -1 (negative one).

Hint: See how to use findIndex() to identify duplicates in an array on the filter section below 👇

filter

The filter() method goes through an array and creates a new array that meets the filter condition(s).

You pass in a callback function that returns a boolean, true or false, and, if true , the array element that passes is added to the new filtered array.

Chain filter() with map() if you want to filter by one property then transform the filtered array.

For example, let’s say we have an array of numbers that contain duplicates. Let’s do two things:

  1. remove the duplicates from the array to get a list of unique values
  2. multiply each item in the array by a factor of 2

The end result should be an array of unique values that are twice the initial array values.

How do we approach this?

Remove duplicates from an array

First, we’ll filter the original array to remove duplicates. There are various ways to achieve this, I’ll show you two of my go-to ways.

const myList = [1, 1, 2, 5, 7, 8, 12, 13, 12, 25, 12];

// Using Set()
const newUnqList = [...new Set(myList)];
console.log(newUnqList) // [object Array] (8) [1,2,5,7,8,12,13,25]

// Using filter() & indexOf()
const newUnqList = myList.filter( (item, index) => myList.indexOf(item) === index );
console.log(newUnqList) // [object Array] (8) [1,2,5,7,8,12,13,25]

The first way uses the spread operator and a Set() to remove duplicates. What’s happening is:

  • Create a Set() instance to remove values that occur more than once in myList.
  • Spread the Set object into an array to use array methods like map() .

The second way uses filter() and indexOf() to remove duplicates. Breaking it down:

  • Loop over each item in myList using filter() , accounting for the index of each item (note the two arguments in the callback).
  • Check if the item’s index in myList is equal to the index from the filter loop. Since indexOf() will return the index of the first occurrence, subsequent duplicates return false in the filter conditional and, so, are excluded.

Transform an array

With our unique array ready, we can move on to transforming it so each value in our new array is double its current value.

const newUnqList = [1,2,5,7,8,12,13,25];

const doubleList = newUnqList.map( item => item * 2 );
console.log(doubleList) // [object Array] (8) [2,4,10,14,16,24,26,50]

Relatively straightforward here, I use map() to return a new array that doubles each value in newUnqList.

Notice that I don’t use return in any of the above callback functions but still don’t get any undefined messages. This is because I’m using an implicit return that helps compact the code by omitting the return keyword.

Implicit returns allow us to replace the curly braces with parenthesis or, even, omit the parenthesis altogether if the return statement can be placed on a single line.

Tip: Be cautious in how you use code shorthand expressions since truncating logic and code can often result to bugs!

Reduce

The reduce() method takes an array and reduces it to a single value.

reduce() accepts a callback function with two parameters:

  1. The thing we’re reducing down to (aka the accumulator)
  2. The variable representing the current value

The return value is used in the next iteration as an accumulator.

Example: Summing up an array of prices 👇

const myList = [10, 20, 50, 70, 80];

const reducedList = myList.reduce( (total, price) => total + price);
console.log(reducedList) // 230

In the example above:

  • total serves as the accumulator, it stores the sum
  • price references each item in the array

Add a second argument to reduce() if you want to specify a starting point, otherwise, Array[0] is used as the initial value.

concat

An alternative to the ES6 spread operator for merging arrays is the concat() method.

concat() takes more than one array as an argument and returns a new array of all the values.

Example: Combine two arrays into a single array inclusive of all values.

const oneList = [1, 1, 1, 1];
const tenList = [10, 10, 10, 10];

const singleList = oneList.concat(tenList);
console.log(singleList) // [object Array] (8) [1,1,1,1,10,10,10,10]

slice

To get a piece (think a subsection) of an array, slice() is the method to go for as it returns a new array with the extracted portion.

Specify a start and end by passing in indices as arguments. Note that the end index is non-inclusive meaning that the last index will be one less than indicated.

splice

slice and splice might sound the same but are in fact quite different.

Unlike slice , the splice() method changes the original array by removing or replacing elements in designated index places.

splice takes the following as arguments:

  • an index location of where the action is to take place
  • a number of items to delete; if none, then use zero
  • an item to insert; if it’s not replacing another item, it will be added right before the indicated index

If no arguments are indicated, the start index will default to undefined and be converted to zero. The array will not be affected.

Otherwise, if no delete items or new/replacement items are indicated but there is a start index passed in, all elements from the indicated index onwards are removed.

Example:

const fruits = ['Apple', 'Orange', 'Banana', 'Dragon Fruit'];
fruits.splice(1, 0, 'Pomegranate'); // Inserts at index 1
console.log(fruits);
// Expected output: Array ["Apple", "Pomegranate", "Orange", "Banana", "Dragon Fruit"]

fruits.splice(4, 1, 'Kiwi'); // Replaces 1 element at index 4
console.log(fruits);
// Expected output: Array ["Apple", "Pomegranate", "Orange", "Banana", "Kiwi"]

Note: The array length changes on the second run since we add “Pomegranate” to the existing fruits list!

That’s it for our quick refresher on JavaScript array methods.

Sabaidi 👋

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Related Posts