简体   繁体   English

无法摆脱JavaScript中的重复项。

[英]Having trouble getting rid of duplicates in JavaScript.

var numberArray = [1,2,3,4, 5,6,7,8,9, 9, 4];
var newArray = [];

function primeChecker(arrayCheck){
    for (var i = 0; i < arrayCheck.length; i++){
        if (Math.sqrt(arrayCheck[i]) % 1 === 0) {
            newArray.push(arrayCheck[i]);
        }

    }

    for (var x = 0; x < newArray.length; x++){
         newArray.sort();
        if (newArray[x] === newArray[x -1]){
            newArray.splice(newArray[x-1]);
        }
    }
}

primeChecker(numberArray);
console.log(newArray);

The returned array is [ 1, 4, 4, 9 ]. 返回的数组为[1,4,4,9]。 The function successfully gets rid of the repeating 9s but I am still left with two 4s. 该函数成功摆脱了重复的9s,但我仍然剩下两个4s。 Any thoughts as to why this might be? 关于为什么会这样的任何想法? I am a JavaScript beginner and not totally familiar with the language. 我是JavaScript初学者,对语言不完全熟悉。

Loop backwards. 向后循环。 When you remove the item from the array the array gets shorter. 当您从数组中删除项目时,数组会变短。

https://jsfiddle.net/2w0k5tz8/ https://jsfiddle.net/2w0k5tz8/

function remove_duplicates(array_){
    var ret_array = new Array();
    for (var a = array_.length - 1; a >= 0; a--) {
        for (var b = array_.length - 1; b >= 0; b--) {
            if(array_[a] == array_[b] && a != b){
                delete array_[b];
            }
        };
        if(array_[a] != undefined)
            ret_array.push(array_[a]);
    };
    return ret_array;
}

console.log(remove_duplicates(Array(1,1,1,2,2,2,3,3,3)));

Loop through, remove duplicates, and create a clone array place holder because the array index will not be updated. 遍历,删除重复项,并创建一个克隆数组占位符,因为不会更新数组索引。

Loop backward for better performance ( your loop wont need to keep checking the length of your array) 向后循环以获得更好的性能(循环无需继续检查数组的长度)

You do not need insert the number that already is in newArray, you can know what element is in the array with the method indexOf. 您不需要插入newArray中已经存在的数字,可以使用indexOf方法知道数组中的元素。 Try it in the if, and you can delete the second cicle for. 在if中尝试,可以删除第二个cicle。 Something like this: 像这样:

 if (Math.sqrt(arrayCheck[i]) % 1 === 0 && newArray.indexOf(arrayCheck[i])==-1) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM