Ad

How To Check For Duplicate Values In An Array And Return The Index In JavaScript?

- 1 answer

I'm making a Battleship game, and in order to test for if two ships are overlapping I made two arrays, one containing all the X position of the blocks the ships occupied, and one contains all the Y position.

I need to somehow know if there are duplicate values in my arrays, and know the index that these duplicates happens. I looked up some of the solutions here, but none works. They mostly contained sort, but sorting changes the order of the values in the array. Is there a way to do this?

Ad

Answer

This is a code to find duplicate elements in an array :

arr = [1, 1 , 2 , 2 , 2 , 3 , 4 , 1 , 5];

for ( i = 0; i < arr.length -1 ; i ++){
    for (j=i+1; j < arr.length; j++ ){
        if (arr[i] == arr[j]){
            console.log("Current element" + arr[i]);
            console.log("initial index:" + i);
            console.log("index:" + j);
        }
    }
}

If you want to compare with another array:

arr = [1, 1 , 2 , 2 , 2 , 3 , 4 , 1 , 5];
arr2 = [1, 2, 3, 4, 4, 4, 5, 2];

for ( i = 0; i < arr.length ; i ++){
    for (j=0; j < arr2.length; j++ ){
        if (arr[i] == arr2[j]){
            console.log("Current element" + arr[i]);
            console.log("initial index:" + i);
            console.log("index:" + j);
        }
    }
}

Hope this helps.

Ad
source: stackoverflow.com
Ad