0

I have a simple class in Node JS

class Animal {
 constructor(name) {
 this.name = name;
 // more fields ...
 }
}
let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects);

What's the best way to check if this array is instanceof Animal objects , without looping over and checking instanceof of each element ?

asked Aug 26, 2021 at 8:29
3
  • Your question is not clear. check if this array is instanceof Animal objects Do you mean check if this array only contains instanceof Animal objects ? Commented Aug 26, 2021 at 8:40
  • @ikhvjs: Exactly! Commented Aug 26, 2021 at 8:40
  • 1
    Then, you still need to loop over all elements in the array for checking. Commented Aug 26, 2021 at 8:42

1 Answer 1

1

Use Array.prototype.every():

class Animal {
 constructor(name) {
 this.name = name;
 // more fields ...
 }
}
let objects = [];
objects.push(new Animal('Dog'));
objects.push(new Animal('Cat'));
objects.push(new Animal('Dinosaur'));
console.log(objects.every(x => x instanceof Animal));

answered Aug 26, 2021 at 8:38

2 Comments

Just to be clear, this still loops over every item in the array
Indeed, and it's not possible without looping

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.