Amir-Mousavi
Amir-Mousavi

Reputation: 4563

javascript (es6) return value of filter in forEach

I have function like below.

If the value of the filter is an array with more than 4 I want to return just the key.

For instance const result = gethitedShips(); // result be 1 or 2 but I get undefined

I totally got confused where to return what

    getHitShips = () => {
    const { players } = this.props;
    return Object.keys(players).forEach(key => {
      const hitShips = players[key].ships.filter(ship => ship.health <= 0);
      if (hitShips.length >= 5) return key;
      return null;
    });
  };

Upvotes: 2

Views: 719

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386746

You could filter the keys by checking the length

const getHitedShips = () => {
    const { players } = this.props;
    return Object
        .keys(players)
        .filter(key => players[key].ships.filter(ship => ship.health <= 0).length >= 5);
};

Upvotes: 3

Related Questions