-1

I have an array here and I have duplicated objects(?) whatever, and i want to console log only one of them based on nick instead both of them. How do I do that?

Snippet:

var _hero = [{
  nick: "Mike",
  lvl: 500,
  x: 10,
  y: 10
}, {
  nick: "Mike",
  lvl: 500,
  x: 10,
  y: 10
}]
let main = () => {
  _hero.forEach(function(_hero) {
    if (_hero.nick == "Mike") {
      console.log(_hero);
    }
  });
};
main();
jerelmiller
  • 1,643
  • 1
  • 10
  • 13
Hiurako
  • 177
  • 2
  • 10

2 Answers2

1

Just to clarify, are you asking how to find the first object in the array that matches a condition (in this case the first object that has nick == "Mike")?

If that is the case, you can use JavaScript's Array.find function that makes this a breeze.

const hero = _hero.find(hero => hero.nick === "Mike")
jerelmiller
  • 1,643
  • 1
  • 10
  • 13
0

Assuming you have multiple heros here and you want one of each you would need to deduplicate your array. You can do this by searching through all indices before a given index, or keeping a dictionary of seen values and checking if you've already seen that hero. Take a look at Remove duplicate values from JS array

ameer
  • 2,598
  • 2
  • 21
  • 36
  • I dont really want to remove dublicate values. All i want to archive is to pick only first object(?) without changing the array pretty much. I've updated my question, maybe it's much cleaner now. – Hiurako Dec 02 '17 at 00:10