数组删除重复的结果 [英] Array Remove Duplicate Results Javascript

查看:129
本文介绍了数组删除重复的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要清除重复的内容。目前的结果是重复的。

I need to remove the duplicates after they are shuffled. Currently the results come out with duplicates.

示例:结果2,2,1,4,4,3,5,5,我需要2,1,4,3,5

Example: Results 2,2,1,4,4,3,5,5, I need as 2,1,4,3,5

这是一个大数组

<script>
Array.prototype.shuffle = function() {
var input = this;

for (var i = input.length-1; i >=0; i--) {

    var randomIndex = Math.floor(Math.random()*(i+1)); 
    var itemAtIndex = input[randomIndex]; 

    input[randomIndex] = input[i]; 
    input[i] = itemAtIndex;

}
return input;
}

var tempArray = [ 

1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,

2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,

3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,

4,4,4,4,4,4,4,4,4,4,4,4,4,

5,5,5,5,5,
]

tempArray.shuffle();

document.write(tempArray);

</script>


推荐答案

而不是使用那个大数组,只需使用 [1,2,3,4,5] .shuffle()。这样,你不会得到重复的。但是这里有一个函数可以给你一个独一无二的数组,即没有重复的数组:

Instead of using that large array, simply use [1,2,3,4,5].shuffle(). This way, you won't get duplicates. But here's a function that will give you a unique array, i.e., an array without duplicates:

function unique(arr) {
  var result = [],
      map = {};
  for (var i = 0; i < arr.length; i++) {
    var duplicate = map[arr[i]];
    if (!duplicate) {
        result.push(arr[i]);
        map[arr[i]] = true;
    }
  }
  return result;
}

然后,只需使用 unique(tempArray.shuffle ))

这是一个 演示

Here's a DEMO.

这篇关于数组删除重复的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆