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

JavaScript之数组去重 #11

Open
heyushuo opened this issue Dec 27, 2019 · 0 comments
Open

JavaScript之数组去重 #11

heyushuo opened this issue Dec 27, 2019 · 0 comments

Comments

@heyushuo
Copy link
Owner

1.利用对象的属性不能相同的特点进行去重(兼容性好)

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = [];
var obj = {};
for (var i = 0; i < arr.length; i++) {
  if (!obj[arr[i]]) {
    obj[arr[i]] = true;
    array.push(arr[i]);
  }
}
console.log(array); //[1, 6, 4, 2, "a"]

2.双层循环 (兼容性好)

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = [];
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < array.length; j++) {
    if (arr[i] == array[j]) {
      break;
    }
  }
  //如果这两个数相等说明循环完了,没有相等的元素
  if (j == array.length) {
    array.push(arr[i]);
  }
}
console.log(array); //[1, 6, 4, 2, "a"]

3.利用 indexOf()

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = [];
for (var i = 0; i < arr.length; i++) {
  if (array.indexOf(arr[i]) == -1) {
    array.push(arr[i]);
  }
}
console.log(array); //[1, 6, 4, 2, "a"]

4.利用 forEach 和 indexOf()

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = [];
arr.forEach(function(item, index) {
  if (array.indexOf(item) == -1) {
    array.push(item);
  }
});
console.log(array); //[1, 6, 4, 2, "a"]

5.利用 filter()和 indexOf()

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = arr.filter(function(item, index) {
  return arr.indexOf(item) == index;
});
console.log(array); //[1, 6, 4, 2, "a"]

6.ES6 的 new Set()实现去重

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
//第一种
var newarr = Array.from(new Set(arr));
console.log(newarr); //[1, 6, 4, 2, "a"]
//第二种
var newarr1 = [...new Set(arr)];
console.log(newarr1); //[1, 6, 4, 2, "a"]

7.ES6 的 includes 实现去重

var arr = [1, 6, 4, 6, 6, 4, 2, "a", "a"];
var array = [];
arr.forEach(function(item, index) {
  if (!array.includes(item)) {
    array.push(item);
  }
});
console.log(array); //[1, 6, 4, 2, "a"]
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

1 participant