DEV Community

Cover image for Tricky Javascript Code part 2
MD ASHRAF
MD ASHRAF

Posted on

Tricky Javascript Code part 2

  1. Find and print the name(s) of user(s) whose age is greater than 30 in nested object. In javascript

Object question image

javascript file

Q1 code image

Output

Image q1 output


2.Flatten an array (input: [1,2,[3,4], 5], output: [1,2,3,4,5])

Solution 1: using flat() method:

const arr = [1, 2, [3, 4], 5]; const flattenedArr = arr.flat(); console.log(flattenedArr); // Output: [1, 2, 3, 4, 5] 
Enter fullscreen mode Exit fullscreen mode

but it will not flatten multiple Levels.

Solution 2: using flat() with Infinity

const arr = [1, 2, [3, 4, [5, 6]], 7]; const flattenedArr = arr.flat(Infinity); console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6, 7] 
Enter fullscreen mode Exit fullscreen mode

Solution 3: using recursion and for loop

function flattenArray(arr) { let result = []; arr.forEach(item => { if (Array.isArray(item)) { result = result.concat(flattenArray(item)); // ---------- OR ------ // result = [...result, ...flattenArray(item)]; } else { result.push(item); } }); return result; } const arr = [1, 2, [3, 4, [5, 6]], 7]; const flattenedArr = flattenArray(arr); console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6, 7] 
Enter fullscreen mode Exit fullscreen mode

Solution 4: using recursion and reduce method

function flattenArray(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val), []); } const arr = [1, 2, [3, 4, [5, 6]], 7]; const flattenedArr = flattenArray(arr); console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6, 7] 
Enter fullscreen mode Exit fullscreen mode

📌📌 More Javascript Tricky questions here:
Tricky Javascript code part 1
Tricky Javascript code - Handling device orientation

Top comments (0)