Jyan Z
Jyan Z

Reputation: 26

Comparing values in the same object

So I'm trying to write some code to check if two people share the same birthday. As you can see person "a" and person "b" do not share the same birthday, but the output on the console is:

a was born on day 1
a has the same birthday as a
a has the same birthday as b
b was born on day 2
b has the same birthday as a
b has the same birthday as b

while it should be:

a was born on day 1
a has the same birthday as a
b was born on day 2
b has the same birthday as b

Code:

var people = {
    a: {
        name: "a",
        birthday: 1,
    },
    b: {
        name: "b",
        birthday: 2,
    }
};


for(var x in people) {
    console.log(people[x].name + " was born on day " + people[x].birthday)
    for(var y in people) {
        if(people[x].birthday = people[y].birthday) {
            console.log(people[x].name + " has the same birthday as " + people[y].name)
        }
    }
}

people[x].birthday = people[y].birthday

seems to be the source of the problem.

Upvotes: 0

Views: 148

Answers (4)

Derek Van Cuyk
Derek Van Cuyk

Reputation: 953

Two problems here:

  1. Your comparison looks like assignment and not equality check

people[x].birthday = people[y].birthday

Should be:

people[x].birthday === people[y].birthday
  1. The second is that in your for loops. You loop through the collection twice starting at the same index (0).

The easiest way would be just to compare the current person with each of the people in the list be

for(var index = 0; index < people.length; index++) {
   console.log(people[x].name + " was born on day " + people[x].birthday)
    for(var inner = index; inner < people.length; inner+1) {
        if(people[index].birthday == people[inner].birthday) {
            console.log(people[index].name + " has the same birthday as " + people[inner].name)
        }
    }
}

Upvotes: 2

cнŝdk
cнŝdk

Reputation: 32145

You just need to use the Identity / strict equality operator === to compare two objects in JavaScript, so you can do :

people[x].birthday === people[y].birthday

Take a look at Comparison operators.

Note:

people[x].birthday = people[y].birthday will always be true because here you are doing an assignment.

Upvotes: 3

Nicolas Plassart
Nicolas Plassart

Reputation: 21

You can use === . this means : equal value and equal type

See more at : http://www.w3schools.com/js/js_comparisons.asp

Regards

Upvotes: 2

indubitablee
indubitablee

Reputation: 8206

people[x].birthday == people[y].birthday

you need == instead of =. = is assignment, == is comparison

by using =, you are assigning people[y].birthday value to people[x].birthday value, and then the two birthdays are the same.

by using ==, you will be comparing if y is the same birthday as x

Upvotes: 5

Related Questions