简体   繁体   中英

Compare two arrays of objects in Javascript

I have a list of co-ordinates of squares of a grid: 网格

Each square is defined by a class:

class Square {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

This is how the app works: First there is a list of randomly generated squares shown, and then the user has to click the squares from memory. (Not necessarily in order)

An example of how the question/answer array would be: (just an example, they are actually randomly generated)

const arr = [new Square(1, 1), new Square(2, 1)]

now, whenever the user clicks on a box, it goes into another array:

var selectedBlocks = [new Square(2, 1), new Square(1, 1)]

In this case, since the squares selected are equal, the function should return true.

What I've tried - I can't manage to get it without a double-for loop O(n^2). Is it possible to optimise for atleast O(n)?

You can use Array.some to find is item already selected or not

 class Square { constructor(x, y) { this.x = x; this.y = y; } } const arr = [new Square(1, 1), new Square(2, 1)]; const selectedBlocks = [new Square(2, 1), new Square(1, 1)]; const isSelected = (block) => { return selectedBlocks.some( (item) => item.x === block.x && item.y === block.y ); }; console.log(isSelected(new Square(2, 1))); console.log(isSelected(new Square(2, 2))); console.log(isSelected(new Square(1, 1)));

Quoting from the answer on another question , the answers to that one may also help. If you just need to know whether A and B has same entries, simply use

JSON.stringify(A.concat().sort()) === JSON.stringify(B.concat().sort())

Link to the original answer is here .

I forgot that there were few built in methods and i wrote this i guess (nlogn) Time complexity code

class Square {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    pri(){
        return this.x + this.y;
    }
}

let inp = [new Square(2,1), new Square(2,3), new Square(1,3)]
let opt = [new Square(1,3), new Square(2,1), new Square(2,3)]

inp.sort((a, b) => {
    return a.pri() - b.pri();
});
opt.sort((a, b) => {
    return a.pri() - b.pri();
});
// assuminng they are of same len
let flag = true
for(i=0; i<inp.length ; i++){
    if(inp[i].x != opt[i].x || inp[i].y != opt[i].y){
        flag = false
        break
    }
}

console.log(flag)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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