Flatten Those Arrays in Javascript

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

Consider below example -

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.

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.

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.

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.

comments powered by Disqus