- Find and print the name(s) of user(s) whose age is greater than 30 in nested object. In javascript
javascript file
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]
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]
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]
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]
📌📌 More Javascript Tricky questions here:
Tricky Javascript code part 1
Tricky Javascript code - Handling device orientation 
 
 
              



 
    
Top comments (0)