Interview question
How do you flatten nested arrays using flat() and flatMap()? flat() और flatMap() से nested arrays को कैसे flatten करें?
Answer
flat() reduces nesting depth into a single-level array, and flatMap() combines map() with a single-level flatten in one efficient pass.
// flat() - default depth of 1
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());
// [1, 2, 3, 4, [5, 6]] - only flattens ONE level deep
// flat(depth) - specify how deep to flatten
console.log(nested.flat(2));
// [1, 2, 3, 4, 5, 6] - flattens 2 levels
// flat(Infinity) - flatten ALL levels regardless of depth
const deeplyNested = [1, [2, [3, [4, [5]]]]];
console.log(deeplyNested.flat(Infinity));
// [1, 2, 3, 4, 5]
// flat() also removes empty slots in sparse arrays
const sparse = [1, , 3]; // hole at index 1
console.log(sparse.flat()); // [1, 3] - hole removed
// flatMap() - map + flatten(1) combined, more efficient than doing both separately
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words); // ['Hello', 'world', 'How', 'are', 'you']
// Without flatMap - requires map then flat separately
const wordsOld = sentences.map(s => s.split(' ')).flat();
console.log(wordsOld); // same result, but two passes over the data
// Practical use: filtering AND transforming, returning multiple or zero items
const numbers = [1, 2, 3, 4, 5];
const doubledEvens = numbers.flatMap(n =>
n % 2 === 0 ? [n * 2] : [] // returning [] effectively filters out odd numbers
);
console.log(doubledEvens); // [4, 8]flat() nesting depth को single-level array में कम करता है, flatMap() map() को single-level flatten के साथ एक ही pass में combine करता है।
// flat() - default depth 1
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());
// [1, 2, 3, 4, [5, 6]] - सिर्फ एक level flatten
// flat(depth) - depth specify करना
console.log(nested.flat(2));
// [1, 2, 3, 4, 5, 6]
// flat(Infinity) - सभी levels flatten
const deeplyNested = [1, [2, [3, [4, [5]]]]];
console.log(deeplyNested.flat(Infinity));
// [1, 2, 3, 4, 5]
// flat() sparse arrays के empty slots भी हटाता है
const sparse = [1, , 3];
console.log(sparse.flat()); // [1, 3]
// flatMap() - map + flatten(1) साथ में
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words); // ['Hello', 'world', 'How', 'are', 'you']
// बिना flatMap के
const wordsOld = sentences.map(s => s.split(' ')).flat();
// Filter और transform साथ - multiple या zero items return करना
const numbers = [1, 2, 3, 4, 5];
const doubledEvens = numbers.flatMap(n =>
n % 2 === 0 ? [n * 2] : []
);
console.log(doubledEvens); // [4, 8]Was this answer clear?