user11805652
user11805652

Reputation:

Comparing objects in an array

I have an array of objects

let pets = [
    {type: 'dog', name: 'Bernie'},
    {type: 'cat', name: 'Bonnie'},
    {type: 'lizard', name: 'heartache'},
    {type: 'dog', name: 'spinach'}
];

I'm writing a function that takes in this array and returns true if all the types are the same and false if not.

Here is what i've tried:

    for (let i = 0; i < pets.length; i++) {
        if (pets[i].type != pets[i + 1].type) {
            return false;
        } else {
            return true;
        }
    }

I thought this would work. Isn't this iterating through the loop and comparing the first object's type with the next?

I've also tried

for(let i = 0;i < pets.length;i++){
      let petOne = pet[i];
      let petNext = pet[i+1];
      if(petOne[i].type != petNext[i].type){
        return false;
      }else{
        return true;
 }
}

I feel like I'm close. How would I go about comparing the pet types and returning true or false.

Upvotes: 0

Views: 57

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

You need to return true only after the loop finishes, else you're returning inside the first iteration regardless.

You also need to make sure that the item after the one you're iterating over exists before comparing, so don't iterate to the very end, iterate to one before the very end.

for (let i = 0; i < pets.length - 1; i++) {
    if (pets[i].type != pets[i + 1].type) {
        return false;
    }
}
return true;

Another approach:

const { type } = pets[0];
return pets.every(p => p.type === type);

Upvotes: 1

Related Questions