0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

7 Comments

The for loop will throw an undefined exception if all type matches. Perhaps you should start with i=1 and then have the comparison as pets[i-1].type != pets[i-].type.
better return !pets.find(p => p.type != type)
@zb' an Array.prototype.some should be more proper in this case.
@ryeballar semantic only, you need boolean and negative match, so anyway it will do the same :) I wantend to point, that we not need to search rest of array if we have match already
@zb' .every doesn't search the rest of the array. .every(condition) is an exact mirror of .some(nnot(condition)) - both stop when the predicate passed in returns a value that makes it senseless to continue. false will stop an .every, while true will stop a some.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.