Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

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

请编写一个数组去重函数(用 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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.