Возврат массива объектов, содержащих информацию об объекте, выбранных из массивов - PullRequest
0 голосов
/ 14 января 2019
            /**
          * A prototype to create Animal objects
          */
        function Animal (name, type, breed) {
            this.name = name;
             this.type = type;
             this.breed = breed;
        }

         function createAnimalObjects(names, types, breeds) {
            // IMPLEMENT THIS FUNCTION!
            }
    /* Input should be like this

    a_name = ['Dog','Cat', 'Fowl','Goat'];
    a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat'];
    a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat'];
    createAnimalObjects(a_name,a_type,a_breed);
    */
    /* *
    [Animal{name:'Dog', type:'Security Dog' ,breed:'German Shepherd'},
Animal{name:'Cat', type:'Blue Eyes', breed:'Noiseless'}
......etc]

Массив должен возвращать новый животный объект, используя приведенный выше прототип. Пожалуйста, помогите комментировать ваш код для ясности. Я ученик.

Ответы [ 2 ]

0 голосов
/ 14 января 2019

Когда вы хотите объединить несколько массивов, это обычно делается с помощью функции zip:

const zip = (...arrays) =>
  [
    ...new Array(
      Math.max(...arrays.map((array) => array.length)),
    ).keys(),
  ].map((index) =>
    arrays.reduce(
      (result, array) => result.concat(array[index]),
      [],
    ),
  );

console.log(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]));

Теперь вы можете использовать zip для объединения массивов, а затем сопоставить их с массивом значений Animal

const zip = (...arrays) =>
  [
    ...new Array(//.keys returns iterator, spread this to new array
      Math.max(...arrays.map((array) => array.length)),//longest array
    ).keys(),
  ].map((index) =>
    arrays.reduce(
      (result, array) => result.concat(array[index]),
      [],
    ),
  );

const a_name = ['Dog', 'Cat', 'Fowl', 'Goat'];
const a_type = ['Security Dog','Blue Eyes','Cock','she Goat'];
const a_breed = ['German Shepherd','Noiseless','African Cock','American Goat'];

function Animal(name, type, breed) {
  this.name = name;
  this.type = type;
  this.breed = breed;
}

console.log(
  //zip returns [[names[0],types[0],breeds[0]],[names[1],types[1],breeds[1],...]
  zip(a_name, a_type, a_breed) 
    .map(
      ([name, type, breed]) =>//destructure [name,type,breed]
        new Animal(name, type, breed),
    ),
);

Некоторая документация: синтаксис деструктуры , распространение , Array.prototype.map и Array.prototype.reduce

0 голосов
/ 14 января 2019

Это простая карта операция

function Animal (name, type, breed) {
    this.name = name;
    this.type = type;
    this.breed = breed;
}

function createAnimalObjects(names, types, breeds) {
    if ([...arguments].some(({length}) => length !== names.length)) throw new Error('length doesnt match');
    return names.map((e, i) => new Animal(e, types[i], breeds[i]));
}

a_name = ['Dog','Cat', 'Fowl','Goat'];
a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat'];
a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat'];

console.log(createAnimalObjects(a_name, a_type, a_breed));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...