Skip to content

第 15 期(2019-05-22):数组去重 #17

@wingmeng

Description

@wingmeng

类型:高频面试题
难度:★★

请编写一个数组去重函数(用 ES5、ES6 各写一个)

function removeRepeat(arr) {
  // 你的代码
}

参考答案:

// 对象属性法
// 注意:[1, '1'] 形式的数组会产生误差,因为 hash[1] === hash['1']
function removeRepeat(arr) {
  var result = [],
      hash = {};

  for (var i = 0, elem; i < arr.length; i++) {
      elem = arr[i];

      if (!hash[elem]) {
          result.push(elem);
          hash[elem] = true;
      }
  }

  return result;
}

// 指针查询法
function removeRepeat(arr) {
  var result = [];

  arr.map(function(item, idx, array) {
    if (array.indexOf(item) === idx) {
      result.push(item);
    }
  });

  return result;
}

// 数组反查法
function removeRepeat(arr) {
  var result = [];

  for (var i = 0; i < arr.length; i++) {
    if (!~result.indexOf(arr[i])) {
      result.push(arr[i]);
    }
  }

  return result;
}

// 过滤法
function removeRepeat(arr) {
  return arr.filter(function(item, idx, array) {
    return array.indexOf(item) === idx;
  });
}

// ES6 Set 去重法
function removeRepeat(arr) {
  return [...new Set(arr)];
}

// 执行效率排行(从高到低):
// 对象属性法 > ES6 Set 去重法 > 数组反查法 > 过滤法 > 指针查询法

本期优秀回答者: @AMY-Y

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions