Programming README

Home


.flat() Method

As its name states, the flat method flattens a nested array to the level we state. The default flattening level is 1, i.e., it flattens a nested array to 1 level (like differentiation - kinda):

Let’s take an example.

// example array:
const arr = [[1, 2, 3], [4, 5, 6], 7, 8]

In this arr, the nest is only 1 level deep, so the default .flat() works:

console.log(arr.flat()); // [1, 2, 3, 4, 5, 6, 7, 8]

On the other hand, something like the following array will require more than 1 level of flattening, since the nest is deeper than just 1 level:

const arrDeep = [[[1, 2], 3], [4, [5, 6]], 7, 8];
console.log(arrDeep.flat()); // [Array(2), 3, 4, Array(2), 7, 8]

For going deeper than 1 level, all we need to do is add the number of levels we want to go within the nested array in the flat bracket:

console.log(arrDeep.flat(2)); // [1, 2, 3, 4, 5, 6, 7, 8]

Like doing: (kinda?)

Practical Example

Let’s consider the following data.

const account1 = {
  owner: 'Charles Barkley',
  activities: [200, 450, -400, 3000, -650, -130, 70, 1300],
  interestRate: 1.2, // %
  pin: 1111,
  username: 'cb',
};
 
const account2 = {
  owner: 'Kenny The Jet',
  activities: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,
  username: 'ks',
};
 
const account3 = {
  owner: 'Ernie Johnson',
  activities: [200, -200, 340, -300, -20, 50, 400, -460],
  interestRate: 0.7,
  pin: 3333,
  username: 'ej',
};
 
const account4 = {
  owner: 'Shaq Shrek',
  activities: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
  username: 'ss',
};

Let’s say that we want to calculate the overall balance of all these people by adding all their account activities. We can do that like this:

const accounts = [account1, account2, account3, account4];
 
const overallBalance = accounts
  .map(acc => acc.activities)
  .flat()
  .reduce((accumulator, element) => accumulator + element, 0);
 
console.log(overallBalance); // 17840

Note: acc here is just a variable inside the bracket to carry out the function. It could be named anything else. I used it to be understood as ‘an individual account of accounts’. Same for accumulator and element.


.flatMap() Method

But what if there’s a shorter way than using .flat() sometimes? Yup, that is the flatMap method.

.flatMap(), like its name suggests, combines .flat() and .map() methods into one. Neat.

So, going back to the practical example from above, we could shorten it like this:

const overallBalance = accounts
  .flatMap(acc => acc.activities)
  .reduce((accumulator, element) => accumulator + element, 0);
 
console.log(overallBalance); // 17840

Caveat

The .flatMap() method can only go 1 level deep to flatten an array. So, if we want to use chaining that includes mapping and flattening for a deeply nested array, we cannot use the .flatMap() method and will have to stick to doing .map(le some kind of transformation).flat(number-of-levels).


Home