0
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 ]. The function successfully gets rid of the repeating 9s but I am still left with two 4s. Any thoughts as to why this might be? I am a JavaScript beginner and not totally familiar with the language.

Blondie
  • 833
  • 5
  • 6

3 Answers3

3

Loop backwards. When you remove the item from the array the array gets shorter.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • This is the simplest solution, but an alternatively is to decrement the loop counter by one whenever an array element is removed. That will keep the counter in sync with the next element to be examined. – Ted Hopp Aug 18 '15 at 14:29
0

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)

THE AMAZING
  • 1,496
  • 2
  • 16
  • 38
0

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. Try it in the if, and you can delete the second cicle for. Something like this:

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