Bootstrap

JavaScript字符串和数组去重方法总结

字符串去重

面试中被问到字符串去重的问题,当时脑子有点空白,下来总结一下:

1. 两层for循环嵌套

新建一个字符串,两层循环,外层循环原字符串,内层循环新字符串,设一个标志位记录源字符串和新字符串的元素是否相等,如果不等,就将元素添加到新字符串中。

function removeRepeatStr(str){
    var newStr = '';
    var flag;
    var len = str.length;
    for(var i=0; i<len; i++){
        flag = 1;
        var newLen = newStr.length;
        for(var j=0; j<newLen; j++){
            if(str[i] == newStr[j]){
                flag = 0;
                break;
            }
        }
        if(flag){
            newStr = newStr + str[i];
        }
    }
    return newStr; 
}
var str='womendeaiwomingbai'
console.log(removeRepeatStr(str)) 

2. 使用indexOf()

基于第一种方法,使用indexof()代替内层循环

function removeRepeatStr (str) {
  var newStr = '';
  var len = str.length;
  for (var i = 0; i < len; i++) {
    if (newStr.indexOf(str[i]) == -1) {
      newStr = newStr + str[i];
    }
  }
  return newStr;
}
var str = 'bilibililalala'
console.log(removeRepeatStr(str)) 

3. search方法

search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。

function removeRepeatStr (str) {
  var newStr = '';
  var len = str.length;
  for (var i = 0; i < len; i++) {
    if (newStr.search(str[i]) == -1) {
      newStr = newStr + str[i];
    }
  }
  return newStr;
}
var str = 'bilibililalala'
console.log(removeRepeatStr(str)) 
4. 利用对象属性

字符串的元素遍历出现过一次就将对象的对应属性值设为1,这样就不会重复。且这样子的时间复杂度我为O(n)。

function removeRepeatStr (str) {
  var obj = {};
  var newStr = "";
  for (var i = 0; i < str.length; i++) {
    if (!obj[str[i]]) {
      newStr += str[i];
      obj[str[i]] = 1;
    }
  }
  return newStr;
}
var str = 'bilibililalala'
console.log(removeRepeatStr(str)) 
5. 将子符串去重转化为数组去重

数组去重

1. 两层for循环嵌套,然后splice去重

两层循环,外层循环数组元素,内层循环比较值,值相同时,删去这个元素。

function unique (arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1)
        j--
      }
    }
  }
  return arr
}
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log(unique(arr))
2. 利用indexOf()去重【或者用includes()也一样】

新建一个数组,外层循环数组元素,内层循环新数组用indexof()代替。

function unique (arr) {
  var array = []
  for (let i = 0; i < arr.length; i++) {
    if (array.indexOf(arr[i]) == -1) {
      array.push(arr[i])
    }
  }
  return array
}
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log(unique(arr))
3. 利用sort()方法去重

利用sort排序后,根据排序后的结果进行遍历及相邻元素比对。

function unique (arr) {
  arr.sort()
  var array = [arr[0]]
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] != arr[i - 1]) {
      array.push(arr[i])
    }
  }
  return array
}
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log(unique(arr))
4. 利用filter()方法去重

indexOf(searchvalue,fromindex)
searchvalue: 必需。规定需检索的字符串值。
fromindex: 可选的整数参数。规定在字符串中开始检索的位置。

function unique (arr) {
  return arr.filter((item, index, arr) => {
    return arr.indexOf(item, 0) === index
  })
}
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log(unique(arr))
5. 利用ES6的Set去重
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log([...new Set(arr)])
6. 利用对象属性

时间复杂度为O(n)

function unique (arr) {
  let obj = {};
  arr.forEach((item) => {
    obj[item] = '';
  })

  return Object.keys(obj)
}
var arr = [1, 2, 3, 1, 4, 5, 2, 6]
console.log(unique1(arr))

数组对象去重

const arr = [
	{'propertyId': 'tyhksxewip', 'propertyName': 'cdkmhb'}, 
	{'propertyId': 'jvbzlgybhq',  'propertyName': 'hiygwcc'},
	{'propertyId': 'jfsmiqda','propertyName': 'wtlfblzz'},
	{'propertyId': 'jvbzlgybhq',  'propertyName': 'hiygwcc'}
];

对propertyId一样的项进行去重。

1. 对象法:数组的 reduce 方法

ie9以下不支持此方法
reduce方法使用

const unique = (arr) => {
    let obj = {}
    let newArr = arr.reduce((prev, cur) => {
        obj[cur.propertyId] ? '': obj[cur.propertyId] = true && prev.push(cur)
        return prev
    }, [])
    return newArr;
}
2. ES6 Map对象
const unique = (arr) => {
  let map = new Map();
  for (let item of arr) {
    if (!map.has(item.propertyId)) {
      map.set(item.propertyId, item);
    }
  }
  return [...map.values()];
};
;