Sunday, 20 April 2025

How to use `Array.prototype.flatMap()` with `destructuring` to unzip an array of pairs into two separate arrays.

 Using `flatMap()` and destructuring, we can achieve this in a neat one-liner.


1. We’re mapping over the indices `[0, 1]`, which correspond to the two elements in each sub-array.

2. For each index, we use `flatMap()` to extract the element at that index from each pair. This gives us one of our desired output arrays.

3. We then use array destructuring `(const [numbers, words] = ...)` to assign the two output arrays to separate variables.


ex: 

const pairs = [[1,’one’],[2,’two’],[3,’three’]];

const  [numbers,words]=[0,1].map(index => pairs.flatMap(pair => pair[index]));


console.log(numbers); // [1,2,3]

console.log(words);    // [‘one’,’two’,’three’]

No comments:

Post a Comment