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

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

Open
wingmeng opened this issue May 22, 2019 · 1 comment
Open

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

wingmeng opened this issue May 22, 2019 · 1 comment

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 22, 2019

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

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

@AMY-Y
Copy link

AMY-Y commented May 23, 2019

        //es5
        function removeRepeatEs5(arr){
            var temp=[];
            for(var i=0;i<arr.length;i++){
                if(temp.indexOf(arr[i])==-1){
                    temp.push(arr[i])
                }
            }
            return temp;
        }
        //es6
        var removeRepeatEs6=(arr)=>{
            return Array.from(new Set(arr));
        }
        var array=[1,1,'1','1',NaN,NaN,null,null,'a',undefined,undefined];
        removeRepeatEs5(array);//无法对NaN去重
        removeRepeatEs6(array);//可对NaN去重

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants