1

Is there an elegant way of calling a method on each object in an array without iteration?

Edit: The intent of the question was to ask "without a for loop, or without any iteration if possible" Sorry for the confusion

var dogs = [new Dog("Max"), new Dog("Buddy"), new Dog("Charlie")];

for(var i=0; i<dogs.length; i++){
    dogs[i].sayName();
}

function Dog(name){

    this.name = name;

    this.sayName = function(){
         console.log(this.name);
    }

}
5
  • 1
    dogs.forEach(dog => dog.sayName());? Commented Aug 18, 2016 at 23:55
  • 2
    To everyone answering this question: isn't forEach() a form of iteration? Commented Aug 19, 2016 at 0:03
  • Sure, it is a form of iteration. Commented Aug 19, 2016 at 0:04
  • Is the intent to ask "without a for loop?" Commented Aug 19, 2016 at 0:04
  • Do you consider recursion to be iteration? Commented Aug 19, 2016 at 0:18

4 Answers 4

4

No

Doing something on each array item means you iterate the array.

So it's not possible to do it without iterating the array.

Sign up to request clarification or add additional context in comments.

Comments

2

Use .forEach()

dogs.forEach(function(elem) {
   console.log(elem.sayName());
}

Alternatively you can use .map(), which returns a new array

dogs.map(function(elem) {
   return elem.name;
}

If you are using array.map() you should return something so you don't end up with a new array of undefined values, if you intend on using the returned array.

Using forEach() seems like a better fit in your use case.

However as @Barmar points out, both methods still iterate over each element in the array.

Comments

0

You could use forEach. Even the object initialisation could be done in a similar way with map:

var dogs = ['Max','Buddy','Charly'].map(name => new Dog(name));
dogs.forEach(dog => dog.sayName());

function Dog(name){
    this.name = name;
    this.sayName = function(){
         console.log(this.name);
    }
}

Comments

0

You can use map:

dogs.map(function(thisDog) { thisDog.sayName(); })

The callback for map takes three arguments: the current value, the current index, and the array. But in your case you only need the current value so you don't need to provide the other two arguments.

1 Comment

map also creates a new Array from the return values of the callback function, which is a bit wasteful as it's not needed. forEach is a better option as it doesn't do that. I wish down voters would spend some time explaining their vote.

Your Answer

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.