数组删除重复结果Javascript

Array Remove Duplicate Results Javascript

本文关键字:结果 Javascript 删除 数组      更新时间:2023-09-26

我需要在混洗后删除重复项。目前的结果是重复的。

示例:结果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())

这是一个演示

function unique(b) {
    for (var c = [], d = {}, a = 0; a < b.length; a++) {
        d[b[a]] || (c.push(b[a]), d[b[a]] = !0);
    }
    return c;
}
unique( [1, 1, 1, 2, 2, 3] ); // [1, 2, 3]

您可以使用以下方法,使用ES6语法:const unique = [...new Set(array)]

有关Set对象的详细信息:Mozilla-设置对象

如果您有权访问jQuery,您可以将进程拆分为两个数组,获取结果,循环通过它,并且只有在它还不存在的情况下才将它添加到newArray中。这样,它们按相同的顺序出现。

var someArray = [3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,2,2];
function cleanArray(oldArray) {
    var newArray = [];
    for(i=0;i<oldArray.length;i++) {
        if( $.inArray(oldArray[i], newArray) == -1 ) {
            newArray.push(oldArray[i]);         
        }
    }
    return newArray;
}
document.write(cleanArray(someArray));
//result would be 3,4,1,2

编辑:我已经更新了功能,所以它的工作方式我相信你的想象。下面是一个工作示例:http://jsfiddle.net/xe2F8/

另外,不要忘记链接到jquery:

    <script src="http://code.jquery.com/jquery-latest.js"></script>

从任何JavaScript数组中删除重复项的一种非常快速的方法是:

var listWithDuplicates = [1, 2, 2, 4, 3, 4, 5, 3, 1, 5];
console.log(listWithDuplicates.filter(function(element, index, array) {
  // using lastIndexOf(...) retains the last
  // repetition preserving the order of the array
  return index === array.indexOf(element);
}));
//prints out: [1, 2, 4, 3, 5] - with indexOf variant
//prints out: [2, 4, 3, 1, 5] - with lastIndexOf variant

希望这对从JavaScript数组中删除重复项的某些目的有用。

请分享有关此解决方案未解决的任何角落案例的反馈,或任何改进此答案的建议。