Skip to content Skip to sidebar Skip to footer

Check If Array Contains 'equal' Object

This is a simplified example, but say I want to generate 5 unique positions on a 100x100 grid. These positions will be stored in an array [[x, y], ...]. The tried the obvious metho

Solution 1:

You can use some() instead of includes() and use join() before compare

while (result.length !== 5) {
    let x = Math.floor(Math.random() * 10) + 1;
    let y = Math.floor(Math.random() * 10) + 1;
    if (!result.some(i => i.join() === [x, y].join())) {
        result.push(array);
    }
}

You can't compare two arrays by simple equality in js. For example []===[] is false. Because both arrays have difference references

console.log([] === []); //false

Same is the case with includes()

let pts = [[1,2],[5,6]];

console.log(pts.includes([1,2])); //falseconsole.log(pts.some(x => [1,2].join() === x.join())); //true

Solution 2:

You can use Array.some() in conjunction with destructuring:

Example:

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

console.log(arr.some(([x, y]) => x === 3 && y === 4));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100%!important; top:0;}

So, your example, can be reworked to this:

let result = [];

while (result.length !== 5)
{
    let x = Math.floor(Math.random() * 10) + 1;
    let y = Math.floor(Math.random() * 10) + 1;

    if (!result.some(([a, b]) => a === x && b === y))
    {
        result.push([x, y]);
    }
    else
    {
        console.log(`${[x,y]} is already on the array!`);
    }
}

console.log(JSON.stringify(result));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100%!important; top:0;}

Post a Comment for "Check If Array Contains 'equal' Object"