# 扁平化数组

function baseFlatten(array, depth, predicate, isStrict, result) {
  predicate || (predicate = isFlattenable);
  result || (result = []);

  if (array == null) {
    return result;
  }

  for (const value of array) {
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        result.push(...value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

result[result.length]可以使得新增变量追加在数组最后一位。

根据depth深度为1时,退出递归。

可以根据predicateisStrict来约束每个参数。

整个函数简短精悍。

# 深度扁平化

无论数组有多少层级,都会完全扁平化。

function flattenDeep(array) {
  const length = array == null ? 0 : array.length;
  return length ? baseFlatten(array, INFINITY) : [];
}

将第二个参数设置为INFINITY,即无限级展平。

最近更新时间: 2020/9/6 11:30:38