Как отфильтровать массив по его значению - PullRequest
1 голос
/ 09 мая 2020

Я создаю каталог персонажей Kingdom Hearts, и у меня есть вопрос, как я могу их отфильтровать

Сначала я создал классы строительства, чтобы сделать персонажей и игры

class character {
    constructor(name, gender, alive,  race, description,debut, seriesAppearance) {
        this.name = name;
        this.gender = gender;
        this.alive = alive;
        this.description = description;
        this.race = race
        this.debut = debut;
        this.seriesAppearance = seriesAppearance;
    }
}

class serie {
    constructor(name, year, chronology) {
        this.name = name;
        this.year = year;
        this.chronology = chronology;
    }
}

Затем я создал персонажей и сами игры

let kh1 = new serie('Kingdom Hearts', '2002', '1')
let khcom = new serie('Kingdom Hearts: Chains of Memories', '2004', '2')
let kh2 = new serie('Kingdom Hearts 2', '2005', '3')

let sora = new character('Sora', 'Male', true, 'Human', 'The Keyblade Master and the protagonist', kh1.name, `${kh1.name}, ${khcom.name} and ${kh2.name}`)
let kairi = new character('Kairi', 'Female', true, 'Human', 'Sora and Riku lost friend', kh1.name, `${kh1.name} and ${kh2.name}`)
let riku = new character('Riku', 'Male', true, 'Human', 'Sasuke of Kingdom Hearts', kh1.name, `${kh1.name} and ${khcom.name}`)
let larxene = new character('Larxene', 'Female', true, 'Nobody', 'Blonde girl who has electrical powers', khcom.name, `${khcom.name} and ${kh2.name}`) 
let axel = new character('Axel', 'Male', true, 'Nobody', 'Man with red hair with fire powers', khcom.name, `${khcom.name} and ${kh2.name}`)
let marluxia = new character('Marluxia', 'Male', true, 'Nobody', 'Pink haired man with a scrythe', khcom.name, khcom.name)
let lexaeus = new character('Lexaeus', 'Male', true, 'Nobody', 'Strong guy who has powers to control the land', khcom.name, `${khcom.name} and ${kh2.name}`)
let vexen = new character('Vexen', 'Male', false, 'Nobody', 'Scientist who created the Riku´s replica', khcom.name, khcom.name)
let replicaRiku = new character('Riku Replica', 'Male', true, 'Replica of the riku that only thinks about protecting Namine', khcom.name, khcom.name)
let namine = new character('Namine', 'Female', true, 'Human', ' Blonde girl who controls people´s memories', khcom.name, khcom.name)
let ansem = new character('Ansem', 'Male', true, 'Nobody', 'Enemy who controlled riku´s mind', kh1.name, kh1.name)

Затем я создал массивы для организации каждого типа символов и общий массив со всеми

let series = [kh1, kh2, khcom]

let heroes = [sora, kairi, namine]
let enemies = [larxene, axel, marluxia, lexaeus, vexen, replicaRiku, ansem]
let ambiguous = [riku]

let characters = [heroes, enemies, ambiguous]

Теперь я хотел бы создать фильтр, который может возвращать все имена живых персонажей, людей или мужчин, поэтому я создал эту тестовую функцию только с людьми, которые не работали

  function human(race) {
      if (this.race == 'Human') {
        return this.name
      }
  }

var humans = heroes.filter(human);

как мне заставить эту функцию работать?

Обновление

этот метод работает для простых массивов

function human(hero) {
    return hero.race === 'Human';
}

const humanNames = heroes.filter(human).map(human => human.name);

Как я могу заставить его работать с массивом символов (массивом массивов)?

1 Ответ

3 голосов
/ 09 мая 2020

Array.prototype.filter передает элемент в функцию обратного вызова и оставляет только те элементы, которые возвращают истинное значение. Вам нужна следующая функция обратного вызова:

function human(hero) {
    return hero.race === 'Human';
}

Если вас интересуют только имена, вы можете сопоставить своих героев с массивом имен:

const humanNames = heroes.filter(human).map(human => human.name);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...