Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多种方式实现数组扁平化 #26

Open
liangbus opened this issue Mar 15, 2020 · 0 comments
Open

多种方式实现数组扁平化 #26

liangbus opened this issue Mar 15, 2020 · 0 comments
Labels

Comments

@liangbus
Copy link
Owner

liangbus commented Mar 15, 2020

  1. 简单递归方式
const normalFlatten = (arr: any[]): any[] => {
  var res = []
  for(let i = 0; i < arr.length; i++){
    let item = arr[i]
    if(Array.isArray(item)) {
      res.push(...normalFlatten(item))
    } else {
      res.push(item)
    }
  }
  return res
}

——————————————————————————————————————————
2. 通过 reduce + 递归方式

const recursiveFlattening = (arr: any[]): any => {
  return arr.reduce(
    (acc, curVal) => {
      return Array.isArray(curVal) ? acc.concat(recursiveFlattening(curVal)) : acc.concat(curVal)
    },
    []
  );
}

——————————————————————————————————————————
3. 用非递归的方式(使用栈)

const arrayFlattening = (arr: any[]): any[] => {
  const stack = [...arr];
  const res = [];
  while(stack.length) {
    const head = stack.shift();
    if (Array.isArray(head)) {
      stack.unshift(...head);
    } else {
      res.push(head);
    }
  }
  return res.reverse();
}

——————————————————————————————————————————
4. 利用 ES6 解构的特性,逐层解构

const awesomeFlatten = (arr: any[]) => {
  while(arr.some(item => Array.isArray(item))){
    console.log(arr)
    arr = [].concat(...arr)
  }
  return arr
}

——————————————————————————————————————————
5. 针对数字类型数组,可以通过 join 和 split 方法即可完成

const numbersFlattening = (arr: number[]): number[] => {
  return arr.join(',').split(',').map(num => Number(num))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant