Home >Web Front-end >JS Tutorial >5 ways to share how to filter out identical elements from arrays in JavaScript

5 ways to share how to filter out identical elements from arrays in JavaScript

黄舟
黄舟Original
2017-05-25 09:22:162057browse

This article mainly introduces the detailed JavaScriptArray 5 ways to filter the same elements. It also introduces 5 practical methods in detail, which is very practical. Value, friends in need can refer to

Method 1: Compare the value of the inner loop variable.

var arr = [1, 2, 3, 1, 3, 4, 5, 5];
var resultArr = [];
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < resultArr.length; j++) {
    if (resultArr[j] == arr[i]) {
      break;
    }
  }
  if (j == resultArr.length) {
    resultArr[resultArr.length] = arr[i];
  }
}
console.log(resultArr); //1,2,3,4,5

Method two: counting method.

var arr = [1, 2, 3, 1, 3, 4, 5, 5];
var count;
var resultArr = [];
for (i = 0; i < arr.length; i++) {
  count = 0;
  for (j = 0; j < resultArr.length; j++) {
    if (resultArr[j] == arr[i]) {
      count++;
      break;
    }
  }
  if (count == 0) {
    resultArr[resultArr.length] = arr[i];
  }
}
console.log(resultArr); //1,2,3,4,5

Method three: flag method (also called hypothesis method)

var arr = [1, 2, 3, 1, 2, 3, 4, 5, 5];
var resultArr = []; //[1,2,3]
var flag;
for (var i = 0; i < arr.length; i++) {
  flag = true;
  for (j = 0; j < resultArr.length; j++) {
    if (resultArr[j] == arr[i]) {
      flag = false;
      break;
    }
  }
  if (flag) {
    resultArr[resultArr.length] = arr[i];
  }
}
console.log(resultArr);//1,2,3,4,5

Method four : Use the sort() method to sort and compare

var arr = [1, 2, 3, 1, 2, 3, 4, 5, 5];
var resultArr = [];
arr.sort(function (a, b) {
  return a - b;
});
//这个时候arr变成了[1, 1, 2, 2, 3, 3, 4, 5, 5]
for (i = 0; i < arr.length; i++) {
  if (arr[i] != arr[i + 1]) {
    resultArr[resultArr.length] = arr[i];
  }
}
console.log(resultArr);

Method 5: Use the filter() method to filter out duplicate arrays

var arr = [1, 2, 3, 1, 2, 3, 4, 5, 5];
var resultArr;
resultArr = arr.filter(function (item, index, self) {
  return self.indexOf(item) == index;

});
console.log(resultArr);

The above is the detailed content of 5 ways to share how to filter out identical elements from arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn