Transform an Array of Objects into an Array of Arrays with .reduce()

Lindsey Kopacz
InstructorLindsey Kopacz

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

We use the same set of data that we used in my filter lesson ( to create an array of coordinates. We use the .reduce() method to create the data structure that we need here.

Instructor: [00:00] Today, we are going to use the reduce method to take this countries variable, which an array of objects, and turn it into a bunch of coordinates. The desired form should be something like this, which is an array of arrays.

[00:16] The first one will be the longitude. The second one will be the latitude. The reason for this is because the particular library I was using prefers this format. Let's jump right in. We're going to create a const called coordinates, and we're going to take the countries variable and reduce it.

[00:39] This takes on a couple of arguments. The first argument is going to be a callback. In this callback, we're going to have the accumulator that we're creating. We're going to call this r, the item. In a lot of examples, I don't see this included, but I'm also going to include an index here.

[00:57] Here, we're creating an array. What this array will be is the accumulator, i.e., r. Let's just console.log the r and the item. If you see here in the console this empty array, that matches up with this empty array after our callback.

[01:23] Because we didn't create anything in the accumulator, nor did we return anything, after every single item, it's going to return undefined. What we're going to do here is we're going to erase this, and we're going to create this array.

[01:43] I'm placing the index here, because I want the length to be exactly the length of our original array. Then I'm going to create an array of item longitude and item latitude. One last thing we got to do, is we have to return the r.

[02:02] Otherwise, it's going to come back as undefined. Save that, refresh, then let's type in coordinates. Now, we have an array of every single coordinate.