前端面试题之数组操作

搜集一些数组操作面试题,后续更新

数组去重

原文:胡哥有话说 https://my.oschina.net/u/4188011/blog/4278961
核心思想,万变不离其宗:

一般创建临时变量tmp,存储不重复的元素(以数组元素存储或对象的键来存储);
遍历待去重数组arr,依次判断tmp中是否包含该元素;
若tmp中不存在该元素,则放入;否则跳过不处理。

方法一

设置tmp为对象,对象的键存储数组元素的值,最终返回对象的所有键。

function array_unique (arr) {
  if (arr.length === 0) {
    return arr
  }
  let tmp = {}
  let len = arr.length
  for (let i = 0; i < len; i++) {
    if (tmp[arr[i]] === undefined) {
      tmp[arr[i]] = i
    }
  }
  return Object.keys(tmp)
}

// 调用数组去重
let arr = [1, 2, 3, 1, 2]
let newArr = array_unique(arr)
console.log(newArr) // ['1', '2', '3']

缺点

  • 你这种方式能区分数字和字符串吗?能区分undefined和’undefined’吗?

  • 你现在返回的数据类型还和原有的数据类型一致吗?

方法二

设置tmp为数组,数组中存储唯一的元素,最终返回tmp

function array_unique (arr) {
  let len = arr.length
  if (!len) {
    return []
  }
  let tmp = []
  for (let i = 0; i < len; i++) {
    // 判断数组arr的元素是否在数组tmp中
    if (tmp.indexOf(arr[i]) === -1) {
      tmp.push(arr[i])
    }
  }
  return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined, 'undefined']
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined']

缺点:

  • 你这方式能筛选NaN吗?

方法三

原理还是同去重方式二,只不过我们使用ES6的includes替换indexOf方法,includes() 方法,判断数组中是否包含某个元素,如果包含返回true,否则返回false

function array_unique (arr) {
  let len = arr.length
  if (!len) {
    return []
  }
  let tmp = []
  for (let i = 0; i < len; i++) {
    // 判断数组arr的元素是否在数组tmp中
    if (!tmp.includes(arr[i]) {
      tmp.push(arr[i])
    }
  }
  return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined,  'undefined', NaN, NaN]
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined', NaN]

缺点:

  • 你的这个筛选方式能区分对象吗?如{}、{a: 1}

方法四

原理同上,我们要继续换一个判断数组是否包含某元素的方法:findIndex
findIndex查询数组是否包含某元素,如果存在返回元素的索引,否则返回-1。它比indexOf更加先进的地方在于能传入callback,按约定方式查询。

function array_unique (arr) {
  let len = arr.length
  if (!len) {
    return []
  }
  let tmp = []
  for (let i = 0; i < len; i++) {
    // 判断数组arr的元素是否在数组tmp中
    if (tmp.findIndex((v) => JSON.stringify(v) === JSON.stringify(arr[i])) === -1) {
      tmp.push(arr[i])
    }
  }
  return tmp
}
let arr = [1, 2, 3, '1', 2, undefined, undefined,  'undefined', NaN, NaN, {}, {}, {a: 1}, {a: 1}]
let newArr = array_unique(arr)
console.log(newArr) // [1, 2, 3, '1', undefined, 'undefined', NaN, {}, {a: 1}]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值