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

2021/02/01 - 实现数组展平 #42

Open
lxinr opened this issue Feb 1, 2021 · 0 comments
Open

2021/02/01 - 实现数组展平 #42

lxinr opened this issue Feb 1, 2021 · 0 comments

Comments

@lxinr
Copy link
Owner

lxinr commented Feb 1, 2021

// 递归实现
function flatten1(array = []) {
  if(!array || !array.length) return array
  var result = []

  for(var i = 0, len = array.length; i < len; i++) {
    if(Array.isArray(array[i])) {
      result = result.concat(flatten1(array[i]))
    } else {
      result.push(array[i])
    }
  }

  return result
}

// toString
// 仅适用于都是string类型或都是number类型的去重
function flatten2(array = [], type = 'number') {
  if(!array || !array.length) return array
  return array.toString().split(',').map(v => type === 'number' ? +v : v)
}

// reduce
function flatten3(array = []) {
  if(!array || !array.length) return array
  const result = array.reduce((acc, cur) => {
    return acc.concat(Array.isArray(cur) ? flatten3(cur): cur)
  }, [])

  return result
}

// es2019 - flat
function flatten4(array = []) {
  if(!array || !array.length) return array
  return array.flat(Infinity)
}



var arr = [1, 2, 3, [4, 5, [6, 7, 8], [9]]]

console.log(flatten1(arr),flatten2(arr), flatten3(arr), flatten4(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant