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

携程:数组去重和数组扁平化(一面) #25

Open
ChuZexx opened this issue May 1, 2019 · 1 comment
Open

携程:数组去重和数组扁平化(一面) #25

ChuZexx opened this issue May 1, 2019 · 1 comment

Comments

@ChuZexx
Copy link

ChuZexx commented May 1, 2019

面试公司:

携程

面试环节:

一面

问题:

1.数组去重
2.数组扁平化

@ChuZexx
Copy link
Author

ChuZexx commented May 1, 2019

一 数组去重

  1. 利用forEach()和indexOf()
// 本质上是利用一层显式遍历和indexOf的隐式遍历,将独一无二的元素放入新数组中返回
Array.prototype.distinct01 = function () {
      const arr = []
      this.forEach(item => {
        if (arr.indexOf(item) === -1) {
          arr.push(item)
        }
      })
      return arr
    }
  1. 利用forEach()和对象容器
// 本质上利用对象来判别元素的唯一性
Array.prototype.distinct02 = function () {
      const arr = []
      const obj = {}

      this.forEach(item => {
        if(!obj[item]){
          arr.push(item)
          obj[item] = true
        }
      })
      return arr
    }
  1. 利用ES6语法Set容器快速实现
// 利用Set自动去重的特性和from将其转回数组
Array.prototype.distinct03 = function(){
      return Array.from(new Set(this))
    }
  1. 利用ES6语法Set和rest语法
// 同样使用Set,并适用rest将其展开
 Array.prototype.distinct04 = function () {
      return [...new Set(this)]
    }

二 数组扁平化

  1. 利用递归 + reduce() + concat()
// 只要判断是数组就进入递归
Array.prototype.flat01= function () {
      return this.reduce((pre, item) => {
        return pre.concat(Array.isArray(item) ? item.flat01() : item)
      },[])
    }
  1. 利用some() + concat()
// 利用some进行判断,只要数组中存在数组,即合并数组,直至循环至数组中无数组
Array.prototype.flat02 = function () {
      let arr = this
      while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr)
      }
      return arr
    }

@acodercc acodercc added this to the 已回答 milestone May 1, 2019
@acodercc acodercc changed the title To JanYiAn:数组去重和数组扁平化(携程) 携程:数组去重和数组扁平化(一面) May 6, 2019
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

2 participants