Home  >  Article  >  Web Front-end  >  JS implementation of simple array deduplication method example

JS implementation of simple array deduplication method example

小云云
小云云Original
2018-01-08 09:16:071702browse

This article mainly introduces the JS implementation of simple array deduplication and array deduplication operations based on the elements in the object, involving the traversal, judgment, appending and other operations of javascript array elements to achieve the deduplication function. Friends in need can refer to the following , hope it can help everyone.

The example of this article describes the JS implementation of simple array deduplication and array deduplication operations based on elements in the object. Share it with everyone for your reference, the details are as follows:

JS array simple deduplication


var arr1 = [1, 2, 3, 4, 5, 6, 3, 4, 3];
function arrayUnique1(arr) {
  var result = [], hash = {};
  for (var i = 0, elem; (elem = arr[i]) != null; i++) {
    if (!hash[elem]) {
      result.push(elem);
      hash[elem] = true;
    }
  }
  return result;
}
console.log(arrayUnique1(arr1));

Result:

js array deduplication based on the elements in the object


##

var arr2 = [
  { name: "name1", num: "1" },
  { name: "name2", num: "11" },
  { name: "name3", num: "12" },
  { name: "name4", num: "13" },
  { name: "name2", num: "1" },
  { name: "name6", num: "12" }
]
function arrayUnique2(arr, name) {
  var hash = {};
  return arr.reduce(function (item, next) {
    hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
    return item;
  }, []);
}
console.log(arrayUnique2(arr2, "name"));
console.log(arrayUnique2(arr2, "num"));

Result:

Related recommendations:

jQuery simple implementation of array deduplication and sorting operations detailed explanation

Use jQuery to deduplicate arrays Duplication and sorting operations

JavaScript array deduplication method

The above is the detailed content of JS implementation of simple array deduplication method example. 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