0

As you can see here I have an array of 2 objects which have the same name and other elements, instead of x,y. I'm trying to console log them, and it works just fine, am getting 2 objects. My question is, how do I console.log only one of them, the first one?

var _hero = [{
  nick: "Mike",
  lvl: 500,
  x: 10,
  y: 10
}, {
  nick: "Mike",
  lvl: 500,
  x: 15,
  y: 15
}]
let main = () => {
  _hero.forEach(function(_hero) {
    if (_hero.nick == "Mike") {
      console.log(_hero);
    }
  });
};
main();

1
  • 3
    umm .. console.log(_hero[0]) Commented Dec 2, 2017 at 9:17

2 Answers 2

2

Use array.find that will give you only the first matching element

var _hero = [{
  nick: "Mike",
  lvl: 500,
  x: 10,
  y: 10
}, {
  nick: "Mike",
  lvl: 500,
  x: 15,
  y: 15
}]

console.log(_hero.find(data=>data.nick ==='Mike'));

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

1 Comment

There was a solution, using foreach method the asker asked
1

Use second parameter in forEach(function(hero, i){... to check the iteration like the following:

var _hero = [{
  nick: "Mike",
  lvl: 500,
  x: 10,
  y: 10
}, {
  nick: "Mike",
  lvl: 500,
  x: 15,
  y: 15
}]
let main = () => {
  _hero.forEach(function(_hero,i) {
    if (_hero.nick == "Mike" && i == 0) {
      console.log(_hero);
    }
  });
};
main();

5 Comments

So simple, damn! Thanks! :)
If you're doing that, what's the point in even using a loop? console.log(_hero[0]);
@nullqube: You can't stop a forEach loop.
@fubar, I have only used OP's code. He might need some other logic to implement on some other iteration.
@Mamun, but this foreach: 1) will not work if first object in array has another nick (more than 2 objects in array, in different order -> 'Mike' is not first) 2) if there are just two objects are in array, no need for loop at all, right? :)

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.