Home > Web Front-end > JS Tutorial > body text

JavaScript 删除数组重复值(去重)的两种方法

WBOY
Release: 2016-06-01 09:54:13
Original
1245 people have browsed it

javascript数组去重方法一:

Array类型并没有提供去重复的方法,如果要把数组的重复元素干掉,那得自己想办法:

方法一:利用indexOf方法;

<code class="language-javascript">var aa=[1,3,5,4,3,3,1,4]
function arr(arr) {
  var result=[]
  for(var i=0; i<arr.length i if result.push console.log arr></arr.length></code>
Copy after login

 

javascript数组去重方法二:

<code class="language-javascript">function unique(arr) {
  var result = [], isRepeated;
  for (var i = 0, len = arr.length; i </code>
Copy after login

方法二,总体思路是把数组元素逐个搬运到另一个数组,搬运的过程中检查这个元素是否有重复,如果有就直接丢掉。从嵌套循环就可以看出,这种方法效率极低。我们可以用一个hashtable的结构记录已有的元素,这样就可以避免内层循环。恰好,在Javascript中实现hashtable是极为简单的,改进如下:

<code class="language-javascript">function unique(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;
}</code>
Copy after login

以上是文章全部内容,希望对码农有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template