This page looks best with JavaScript enabled

Flatten Those Arrays in Javascript

 ·   ·  ☕ 2 min read

Flatten arrays easily with a single command. Or, go further than that by using a map function while flattening arrays.

Consider below example -

1
const nums = [[0, 2], [1, 3], [7, 9, 11]];

You can choose to iterate through all elements if you want to iterate through or access all numbers, or you could just use flat.

1
2
3
const nums = [[0, 2], [1, 3], [7, 9, 11]];
console.log(nums.flat());
// [ 0, 2, 1, 3, 7, 9, 11]

A real-world example - you receive a file that may have a one or more comma-separated ‘student ids’ in a single column. One of the quickest way to process and sort those ids is by having them in a single array - so flatten them up.

1
2
3
4
5
6
const ids = [[1001, 2001], [1013, 1063], [1127, 1013, 1929, 1211]];

const newIds = feeDue(ids);

console.log(newIds.flat().sort());
// [ 1001, 1013, 1013, 1063, 1127, 1211, 1929, 2001 ]

You can then process the elements to apply a prefix or ‘do some such thing’. Alternatively, combine map and flat to do two things in one go.

1
2
3
4
5
6
7
const ids = [[1001, 2001], [1013, 1063], [1127, 1013, 1929, 1211]];

console.log(
  ids.flatMap(id => {
    //logic to look up whether fee is due
  }).sort();
)

flatMap applies map first, and flattens array on the mapped array.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things