面试中可能遇到的数组问题

数组去重

利用对象属性不能重复的特性

Array.prototype.distinct = function () {
  console.log(this);
  let arrObj = {};
  let newArr = [];
  for (const key of this) {
    if (!(arrObj[key])) {
      arrObj[key] = 1;
      newArr.push(key);
    }
  }
  console.log(newArr);
  return newArr;
};
[1, 2, 5, 3, 6, 1, 2, 6, 9].distinct();

使用递归,先排序,再递归比较

Array.prototype.distinct = function () {
  let arr = this;
  arr.sort(function (a, b) {
    return a - b;
  });

  function loop(index) {
    // 判断到数组第二个元素即可停止
    if (index >= 1) {
      if (arr[index] === arr[index - 1]) {
        arr.splice(index, 1);
      }
      loop(index - 1);
    }
  }
  loop(arr.length - 1);
  return arr;
};
console.log([1, 2, 5, 3, 6, 1, 2, 6, 9].distinct());

利用ES6 默认的set数据结构,类似数组,但是值是唯一的

function distinct(arr) {
  return Array.from(new Set(arr));
};
// 或者和展开运算符一起使用
function distinct1(arr) {
  return [...new Set(arr)];
};
console.log(distinct([1, 2, 5, 3, 6, 1, 2, 6, 9]));
console.log(distinct1([1, 2, 5, 3, 6, 1, 2, 6, 9]));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容