본문 바로가기
Front End/JavaScript

[JS] The Complete JavaScript Course 2021: From Zero to Expert! | # 165

by 옐 FE 2021. 6. 8.

Test Data

const dogs = [
  { weight: 22, curFood: 250, owners: ['Alice', 'Bob'] }, 
  { weight: 8, curFood: 200, owners: ['Matilda'] },
  { weight: 13, curFood: 275, owners: ['Sarah', 'John'] }, 
  { weight: 32, curFood: 340, owners: ['Michael'] },
];

 

Your tasks:

1. Loop over the 'dogs' array containing dog objects, and for each dog, calculate the recommended food portion and add it to the object as a new property. Do not create a new array, simply loop over the array. Forumla: recommendedFood = weight ** 0.75 * 28. (The result is in grams of food, and the weight needs to be in kg) -> task 1로 각  object에 'recFood' 추가

 

3 .Create an array containing all owners of dogs who eat too much ('ownersEatTooMuch') and an array with all owners of dogs who eat too little ('ownersEatTooLittle').

 

 


 

 

callback Function 작성할 때마다 어떤 것을 parameter로 써야하는 지 감을 못 잡고, 혼자서 끙끙 앓았던 문제.

 

간단하게 하나씩 풀어갈 생각을 하면 되었는데도 Array.reduce()를 쓸 수 있을지 않을까 코드 작성해보다가 결국 막히고 해설영상을 보았더니 filter와 flatMap으로 작성하시더라... dogs가 Array로 구성 되어있어서 dog를 parameter로 넘겨주면 해결되는 매직-!

const ownersEatTooMuch = dogs
  .filter(dog => dog.curFood > dog.recFood)
  .flatMap(dog => dogs.owners);
    
const ownersEatTooLittle = dogs
  .filter(dog => dog.curFood < dog.recFood)
  .flatMap(dog => dogs.owners);
  
console.log(ownersEatTooMuch, ownersEatTooLittle);

일단은 'dogs'를 조건에 맞게 나누고 그 안에서 'owners'를 찾아 각각 하나의 Array로 만들어주기.

chain으로 엮어져 있기 때문에 어느 method를 먼저 사용할지도 고려해야한다.

댓글