Categories
JavaScript Basics

Ways to Iterate or Combine JavaScript Arrays Entries

Spread the love

There’re many ways to do things with JavaScript. For instance, there’re lots of ways to iterate through the items of an array.

In this article, we’ll look at ways to iterate through and combine items inside arrays.

Array.prototype.reduce

The array instance’s reduce method is used to combine the entries in an array into one value.

It takes up to 2 arguments. The first is a callback that takes the combined value so far as the first parameter and the current value being processed as the 2nd parameter.

The 3rd parameter is the index of the current value and the last is the original array. These 2 are both optional.

The 2nd argument is the initial value to be used for the combined value.

For instance, we can use it to sum up all the items in the array as follows:

const result = [1, 2, 3].reduce((a, b) => a + b, 0);

In the code above, we called reduce on [1, 2, 3] and compute the sum of the entries by passing in:

(a, b) => a + b

where a is the sum so far, and b is the current item being processed. 0 is the initial value of the sum.

Then result should be 6 since it’s the sum of all the numbers in the array.

Array.prototype.join

The join method combines all the array entries into a string, separated by a separator of our choice.

It takes one argument, which is a string with the separator we want to use.

For instance, we can use it as follows:

const result = [1, 2, 3].join(',');

Then we get 1,2,3 for result .

ES2018 for await of Loop

The for...await...of loop is used to iterate through promises to make sure that they are completed in sequence.

It’s like for...of but it’s for promises. For instance, we can use it as follows:

const promises = [1, 2, 3, 4, 5].map(a => new Promise((resolve) => setTimeout(() => resolve(a), 1000)));

(async () => {
  for await (const p of promises) {
    console.log(p);
  }
})()

In the code above, we have an array of promises, and we used the for...await...of loop to resolve them one at a time.

So we should see the numbers 1 to 5 logged in the console after a 1-second delay, as we specified in the setTimeout function.

Array.prototype.flat

The array instance’s flat method lets us flatten an array by reducing the depth of the array. It takes an argument with a positive number to specify the number of levels to flatten. Or we can specify Infinity to recursively flatten an array.

It returns a new flattened array.

For instance, we can use it as follows:

const arr = [
  [
    [1], 2, 3
  ]
];

const flattened = arr.flat(1);

In the code above, we have an array that has nested arrays in it. Then when we call flat on it with 1 as the argument, we get that flattened is :

[
  [
    1
  ],
  2,
  3
]

If we specify Infinity as its argument as follows:

const flattened = arr.flat(`Infinity`);

We get:

[
  1,
  2,
  3
]

as the value of flattened .

Array.prototype.flatMap

The flatMap method calls map then flat . It can flatten by 1 nesting level only after doing the mapping.

For instance, if we have:

const arr = [
  1, 2, 3
];

const flattened = arr.flatMap(a => [a * 2]);

Then flattened is:

[
  2,
  4,
  6
]

since we mapped the entries by multiplying each by 2, and then we put each in their own array.

Then the flat part of flatMap flattens the individual arrays so that we get back the entries that have no array in it.

If we write:

const arr = [
  1, 2, 3
];

const flattened = arr.flatMap(a => [[a * 2]]);

Then we get:

[
  [
    2
  ],
  [
    4
  ],
  [
    6
  ]
]

as the value of flattened since flatMap only flattens up to one level.

Conclusion

The array flat method lets us flatten an array as many levels as we like by flattening any nested arrays.

The flatMap method does the same thing as map and flat(1) one after the other.

The for...await...of loop lets us complete an array of promises in sequence.

Array instance’s reduce method lets us combine the values in an array into one.

The join method lets us combine array entries into one as a string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *