Skip to content

Instantly share code, notes, and snippets.

@mihansweatpants
Created June 3, 2019 09:51
Show Gist options
  • Select an option

  • Save mihansweatpants/2acc97872842a3b61c9f961f8ed8f7b3 to your computer and use it in GitHub Desktop.

Select an option

Save mihansweatpants/2acc97872842a3b61c9f961f8ed8f7b3 to your computer and use it in GitHub Desktop.

Развернуть многомерный массив

flat([1, 2, [3, 4]]); // [1, 2, 3, 4]
flat([1, 2, [3, [4]]]); // [1, 2, 3, 4]

Вложенность не ограничена.

Решение

Array.prototype.reduce + рекурсия

function flat(arr) {
  return arr.reduce((acc, curr) => {
    if (Array.isArray(curr)) {
      return [...acc, ...flat(curr)];
    } else {
      return [...acc, curr];
    }
  }, []);
}

Вариант без рекурсивных вызовов (стэк)

function flatNonRecursive(arr) {
  const stack = [...arr];
  const result = [];

  while (stack.length) {
    const next = stack.pop();
    if (Array.isArray(next)) {
      stack.push(...next);
    } else {
      result.push(next);
    }
  }

  return result.reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment