DEV Community

Saurav Gupta
Saurav Gupta

Posted on

Different ways to Flatten the array in JavaScript

Using Reduce

function flatten(arr) {
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc = [...acc, ...flatten(item)];
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
}
Enter fullscreen mode Exit fullscreen mode

Using Recursion

function flattenRecursion(arr) {
  if (!arr.length) return [];
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (Array.isArray(item)) {
      res = [...res, ...flattenRecursion(item)];
    } else {
      res.push(item);
    }
  }
  return res;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)