我需要在洗牌后删除重复项。目前结果有重复。
示例:结果 2,2,1,4,4,3,5,5,我需要为 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()
即可。这样,您就不会得到重复的内容。但这里有一个函数,它将为您提供一个唯一的数组,即一个没有重复的数组:
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())
。
这是一个 DEMO 。
关于javascript - 数组删除重复结果 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12166205/