×
Community Blog Iteration Methods in JavaScript Arrays

Iteration Methods in JavaScript Arrays

This article takes a detailed look at the iteration methods of JavaScript arrays.

By Alex Muchiri.

When working with JavaScript as a developer, you will interact with several different methods for iterating over arrays. A JavaScript array can consist of listed elements, and various methods can used to either mutate the array, or in most cases, return a new array. Being able to operate on the arrays in a functional way is important given the contiguous nature of the listed items.

Iteration methods can enable the operation of an array in an atomic way to return a distinct new array. Many built-in methods in JavaScript exist specifically for operating on arrays. Among these, there's mutator methods, which modify an existing array, and there's also accessor methods, which return entirely new values. Last, there's iteration methods, which operate over all array items in a separate and sequential manner. In this blog post, my focus will be on the last category, iteration methods.

Each time when an iteration method is called, a callback function is required that operates sequentially on separate, individual items. Since there are different array methods, all callbacks need distinct arguments such as the value type that it returns. As such, the value to be returned has a determinant effect on the end value to be returned in the entire array operation except when handling forEach. An iteration method, in some cases, may end the iteration before all listed items are completed but that will only happen in special cases.

In the remainder of this article, let's look at some of the iteration methods found in JavaScript. For each one, we will breakdown how the method works and further illustrate with examples.

forEach:

When the forEach() method is summoned, it will call a function for all the individual elements. Here is a breakdown of how this method works:

  • The callback type: This produces an item that may or may not be taken through further processes.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: There is no defined return value.

Consider the example below:

[5, 6, 7].forEach(function (item, index) {
  console.log(item, index);
});

Here is another example:

    var fish = [ "tuna", "tilapia", "shark"];
    fish.forEach(function(elem) {
        console.log(elem);
    });

A notable disadvantage with forEach() is a lack of support for break. However, you can substitute this method for the every() method:

    function breakAtEmptyString(arr) {
        arr.every(function(elem) {
            if (elem.length === 0) {
                return false; // break
            }
            console.log(elem);
            return true; // this is important!
        });
    }

When every() has been used, the returned value is false if there is a break, and true if otherwise. The advantage of using this over the simple for loops is that you're able to react to a successful iteration process. However, you can only continue onwards if the returned value is true.

It gets even more interesting here because we can substitute both with some() and break by returning true.

    function breakAtEmptyString(arr) {
        arr.some(function(elem) {
            if (elem.length === 0) {
                return true; // break
            }
            console.log(elem);
            // this is an implicit case: return undefined if false
        });
    }

find:

  • The callback type: This returns a prediction of either true or false.
  • The callback: This is used to know if the item is what is being sought.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is an item that meets set criteria. The iteration stops when the value returned is true.

Consider the example below:

const letters = [{ id: 'x' }, { id: 'y' }, { id: 'z' }];
const identity = letters.find(function (item) {
  return item.id === 'y';
});
console.log(found === letters[1]); // true

Let's test this method using our fruits example again.

let allFruits = [ "apple", "banana", "orange", "strawberry", "pear"];

Now let's use the find() method to separate the fruits using a simple criteria. For this, it will be berries.

const isBerry= berry => {
    return [ "strawberry", "blueberry" ].includes(berry);
}
allFruits.find(isBerry);

The output is the following:

strawberry

The find() method has determined that strawberry satisfied the isBerry test.

findIndex:

  • The callback type: This returns a prediction of either true or false.
  • The callback: This is used to know if the item is what is being sought.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is an index of the item that meets set criteria, or -1. The iteration stops when the value returned is true.

Consider the example below:

const letters = [{ id: 'x' }, { id: 'y' }, { id: 'z' }];
const foundIndex = letters.findIndex(function (item) {
  return item.id === 'y';
});
console.log(foundIndex === 1); // true

Let's try the method using our fruits example another time:

let allFruits = [ "apple", "banana", "orange", "strawberry", "pear", "blueberry",];

And let's use the findIndex() method to find the index number of the fruits using a simple criterion: which one are berries and which ones are not.

const isBerry= berry => {
    return [ "strawberry", "blueberry" ].includes(berry);
}
allFruits.findIndex(isBerry);

The output is the following:

2

The returned value is -1 if the test criterion is not met.

const isMango = mango => {
    return [ "mango" ].includes(mango);
}

allFruits.findIndex
Output
-1

This last method is useful for handling arrays with very many lists.

map:

  • The callback: This returns an item and seeks to replace the item in the list with a different item.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is a list or array of new items.

Consider the example below:

const four = [4, 5, 6];
const doubled = four.map(function (item) {
  return item * 2;
});
console.log(four === doubled, doubled); // false, [8, 10, 12]

Further, with the map() method, it is possible to print in the console the iterations of a loop. Since the map() method returns a new array, it needs to be assigned to a new variable. Consider the example below:

let fruit = [ "apple", "banana", "pear", "orange" ];

// to print individual items in the array
let printFruit = fruit.map(individualFruit => {
    console.log(individualFruit);
});

printFruit;

The output is the following:

apple
banana
pear
orange

Similarly, the method can be applied to change the value for items in an array separately. Let us try a simple method where we add -en to all the items in our array.

let simpleFruit = fruit.map(individualFruit => {
    return `${individualFruit}-en`;
});

simpleFruit;
Output
[ 'apple-en', 'banana-en', 'pear-en', 'orange-en' ]

We have now modified the individual items contained in the fruit in the simpleFruit but the original list remains.

filter:

  • The callback type: This returns a prediction of either true or false.
  • The callback: This is used to know if it should retain or discard the value.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is a list or array of retained items.

Consider the example below:

const numbers = [4, 5, 6];
const evens = numbers.filter(function (item) {
  return item % 5 === 0;
});
console.log(numbers === evens, evens);

In a more practical application, the filter() method can list items that meet a specified criteria such as those names containing a particular letter. The method here is known as string indexing. Now let's try out this method with our fruit example:

let allFruits = [ "apple", "banana", "pear", "orange" ];

// Filter the fruits whose names contain an "e" 
let filteredFruits = allFruits.filter(fruit => {
  return fruit[0] === "e";
});

filteredFruits;
Output
[ 'apple', 'pear', 'orange' ]

reduce:

  • The callback type: This passes the result of previous iteration to the next one.
  • What the callback gets: The callback obtains the result, item, index, and list.
  • Returned value: The returned value is a result from previous iteration.

This method may have an initialValue as an option after the reducer, but the first item is taken by default if no such condition is set.

Consider the example below:

const sum = [4, 5, 6].reduce(function (result, item) {
  return result + item;
}, 0);

In most cases, this method will be used with numbers. See how we add the following numbers in an array:

let numbers = [ 2, 3, 6, 5, 7, 9 ];

// Use the method to obtain a sum of all numbers in the array
let sum = numbers.reduce((a, b) => {
    return a + b;
});

sum;
Output
32

reduceRight:

This method is quite similar to reduce except that it works in reverse. As was in the previously discussed method, this method will be used with numbers. Consider the example below to see how we add the following numbers in an array:

let numbers = [ 2, 3, 6, 5, 7, 9 ];

// Use the method to obtain a sum of all numbers in the array
let sum = numbers.reduceRight((a, b) => {
    return a + b;
});

sum;
Output
32

There is no difference in the result, but if we change the signs of some of the numbers, there is a possibility of a different result.

some:

  • The callback type: This returns a prediction of either true or false.
  • The callback: This is used to know if the item meets the set criteria.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is either true or false depending on whether the first item meets set criteria. The iteration stops when the value returned is true.

Consider the example below:

const hasComplexNumbers = [1, 2, 3, i, 4].some(function (item) {
  return item < 0;
});
console.log(hasComplexNumbers); // true

every:

  • The callback type: This returns a prediction of either true or false.
  • The callback: This is used to know if the item meets the set criteria.
  • What the callback gets: The callback obtains the item, index, and list.
  • Returned value: The returned value is either true or false depending on whether the first item meets set criteria. The iteration stops when the value returned is false.

Consider the example below:

const allNegativeNumbers = [-1, -2, -3, 6, -9].every(function (item) {
  return item > 0;
});
console.log(allNegativeNumbers); // true

Conclusion

This article has reviewed to a considerable depth the most widely used iteration methods for handling JavaScript arrays. You should now have easier time when looping through arrays, filtering and reducing, mapping items in an array as well as finding items and their indices.

Do you have an Alibaba Cloud account? Sign up for an account and try over 40 products for free. This deal is worth up to $1300. Get Started with Alibaba Cloud to learn more.

The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Clouder

1,863 posts | 372 followers

You may also like

Comments