Search code examples
javascriptfor-looparraylistsplice

.splice() removes item from two arrays - delete duplicates from array


I want to remove duplicates from an array, so I wrote code with two for loops.

let MainArray = [{
            "name": "banana",
            "lat": 3,
            "lng": 3
        },
        {
            "name": "apple",
            "lat": 3,
            "lng": 3
        },
        {
            "name": "car",
            "lat": 1,
            "lng": 1
        },
        {
            "name": "bike",
            "lat": 1,
            "lng": 1
        }
    ];

    let ArrayCopy = MainArray;

    console.log(MainArray.length);
    console.log(ArrayCopy.length);

    for (let i = 0; i < MainArray.length; i++) {

        for (let x = 0; x < ArrayCopy.length; x++) {

            if ((MainArray[i].name !== ArrayCopy[x].name) && ((MainArray[i].lat === ArrayCopy[x].lat) || (MainArray[i].lng === ArrayCopy[x].lng))) {

                //some output

                ArrayCopy.splice(x, 1);
            }
        }
    }

    console.log(MainArray.length);
    console.log(ArrayCopy.length);

I want to avoid, that the results match twice. For example:

result 1: banana & apple

result 2: apple & banana

That's why I want top splice the match from ArrayCopy.

Before the loop starts the length of MainArray and ArrayCopy are both 4, but after the loop both arrays length are 2.

Why does the length of MainArray change?


Solution

  • The second array is the same object as the original array. To copy the array, you need to create a new array, and append the new array with the items from the first array.Below we use the spread operator to fill a new array with all the values from the main array.

    let MainArray = [{
                "name": "banana",
                "lat": 3,
                "lng": 3
            },
            {
                "name": "apple",
                "lat": 3,
                "lng": 3
            },
            {
                "name": "car",
                "lat": 1,
                "lng": 1
            },
            {
                "name": "bike",
                "lat": 1,
                "lng": 1
            }
        ];
    
        let ArrayCopy = [...MainArray];
    
        console.log(MainArray.length);
        console.log(ArrayCopy.length);
    
        for (let i = 0; i < MainArray.length; i++) {
    
            for (let x = 0; x < ArrayCopy.length; x++) {
    
                if ((MainArray[i].name !== ArrayCopy[x].name) && ((MainArray[i].lat === ArrayCopy[x].lat) || (MainArray[i].lng === ArrayCopy[x].lng))) {
    
                    //some output
    
                    ArrayCopy.splice(x, 1);
                }
            }
        }
    
        console.log(MainArray.length);
        console.log(ArrayCopy.length);

    You can also use the slice method to return an array of all the items by not passing any parameters.

    const clone = originalArray.slice()