Fighters Game Example

Let's say we have an array of objects representing the different fighters in the game, with each object containing properties like the fighter's name, attack power, and health points. Here's an example of such an array:

const fighters = [
  { name: "Ryu", attack: 80, hp: 100 },
  { name: "Chun-Li", attack: 90, hp: 120 },
  { name: "Guile", attack: 70, hp: 110 },
  { name: "Zangief", attack: 100, hp: 130 }
];

Now, let's say we want to create a new array that contains the names of all the fighters with more than 100 health points. We can use the map() method to do this by calling map() on the fighters array and passing a function that extracts the name property from each object and returns it. Here's how we could do this:

const toughFighters = fighters.map(fighter => fighter.name);

console.log(toughFighters); // Output: ["Ryu", "Chun-Li", "Guile", "Zangief"]

The toughFighters array now contains the names of all the fighters in the fighters array. If we wanted to filter the array to only include fighters with more than 100 health points, we could use the filter() method in combination with map() like this:

const toughFighters = fighters
  .filter(fighter => fighter.hp > 100)
  .map(fighter => fighter.name);

console.log(toughFighters); // Output: ["Chun-Li", "Zangief"]

In this example, filter() is used to create a new array that only includes fighters with more than 100 health points, and then map() is used to create a new array that contains the names of those fighters.

Last updated