[JavaScript 30 Days Challenge] Array Cardio Day 1

yuza🍊·2021년 10월 7일
0
post-thumbnail

DAY 4-Array Cardio Day 1

CODE

기본 구현 사항: 다양한 Array methods를 사용하며 문제를 해결하기

1) Filter the list of inventors for those who were born in the 1500's: inventors 배열을 '1500년 대에 태어난 사람들'을 기준으로 필터링하라.

const inventors = [
      { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
      { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
      { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
      { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
      { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
      { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
      { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
      { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
      { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
      { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
      { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
      { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
];

const answer1 = inventors.filter(
        (inventor) => inventor.year >= 1500 && inventor.year < 1600
);

console.table(answer1);

  • filter()는 내부의 함수를 통과하는(만족하는) 모든 요소를 모아 새로운 배열로 반환하는 메소드이므로 year 속성이 1500 이상 1600 미만인 inventors만 걸러지게 된다.

2) Give us an array of the inventors first and last names: inventors의 첫번째, 마지막 이름을 콘솔에 출력하라.

inventors.map((inventor) =>
        console.log(`First: ${inventor.first}, Last: ${inventor.last}`)
);

  • map() 메소드를 통해 배열을 순회하며 각 요소들에 주어진 함수를 적용한 결과들을 모아 새로운 배열을 반환한다. 따라서 각 inventor의 first, last 속성을 콘솔에 출력할 수 있다.

3) Sort the inventors by birthdate, oldest to youngest: inventors를 생년에 따라 가장 나이 든 사람부터 젊은 사람 순으로 정렬하라.

const earliest = inventors.sort(function (a, b) {
        return a.year - b.year;
});

console.table(earliest);

  • sort() 메소드는 사용법에 대해 이번에야 말로 좀 확실히 잡고 가고 싶다. sort() 메소드 내의 함수의 리턴값을 토대로 요소들을 정렬하는데, 예를 들어
const numbers = [1,3,2,4,5]; 
numbers.sort(function(a, b) { 
    return a - b;
});

다음과 같은 코드가 있을 때, a-b가 0보다 작을 경우, a를 b의 앞에 두게 된다. a-b가 0인 경우에는 a와 b의 순서를 변경하지 않으며, a-b가 0보다 클 경우, a를 b의 다음 순서로 변경한다.

const numbers = [1,3,2,4,5]; 
numbers.sort(function(a, b) { 
    return b - a;
});

다음과 같은 경우엔 정확히 반대로 동작한다. b-a가 0보다 작은 경우, a를 b의 앞에 둔다. 즉, 더 큰 값인 a가 더 작은 값인 b보다 앞에 오게 되면서 내림차순 정렬이 되는 것이다. 위와 같이 b-a가 0이면 순서 변경이 없으며, b-a가 0보다 크면 더 큰 값인 b를 a보다 앞에 두게 되며 동일하게 내림차순으로 정렬이 된다.

4) How many years did all the inventors live all together?: 모든 inventors가 살아있었던 기간을 모두 더하라.

// 나의 코드
const reducer = (prev, current) => prev + current;

      console.log(
        inventors
          .map((inventor) => inventor.passed - inventor.year)
          .reduce(reducer)
);

// 정답 코드
const totalYears = inventors.reduce((total, inventor) => {
      return total + (inventor.passed - inventor.year);
}, 0);

  • 위 이미지를 참고해보자면, 정답 코드의 초기값이자 첫번째 호출 시의 accumulator(='total') 값은 0이 된다. inventor는 inventors 배열의 첫번째 객체인
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },

가 될 것이다. 첫 번째 호출의 리턴값은 0 + (1955 - 1879)가 될 것이다.
두 번째 호출의 리턴값은 76 + (1727 - 1643) = 160이 될 것이며 세 번째 ... 마지막 호출까지 다음과 같은 방식으로 모든 inventors의 나이가 더해지게 될 것이다.

reduce() 메소드는 처음 사용해보는 거라 좀 낯설었지만, 문서를 확인해보니 이해가 가는 것 같다.

5) Sort the inventors by years lived: inventors를 나이 순으로 정렬하라.

const oldest = inventors.sort(function (a, b) {
        const inventorA = a.passed - a.year;
        const inventorB = b.passed - b.year;
        return inventorA - inventorB;
});

console.table(oldest);
  • 이전 정렬 문제와 동일하게 sort() 메소드를 사용했는데, 다만 inventors의 나이를 비교해야 했으므로 중간에 inventorA, inventorB 변수를 추가로 생성하여 그 안에 비교할 두 inventors의 나이를 계산에 할당하였고, 그 변수를 사용하여 뻴셈을 함으로써 나이를 비교하였다.

6) Sort the people alphabetically by last name: 사람들의 이름을 last name의 알파벳 순으로 정렬하라.

const people = [
        "Bernhard, Sandra",
        "Bethea, Erin",
        (...생략...)
        "Becker, Carl",
        "Biondo, Frank",
];

const sortedPeople = people.sort(function (a, b) {
        const lastNameA = a.split(", ")[1];
        const lastNameB = b.split(", ")[1];
        return lastNameA < lastNameB ? -1 : 1;
});

console.table(sortedPeople);
  • sort() 메소드는 알파벳 순으로도 정렬을 해준다. 5번 문제와 유사하게, sort() 메소드 내 함수에서 변수 lastNameA, lastNameB를 생성하여 people의 마지막 이름을 할당한다. 그리고 그 변수들끼리 서로 비교하여 만약 lastNameB가 더 크면 -1을(즉, 더 작은 lastNameA를 더 큰 lastNameB보다 앞에 오도록 = 오름차순), 작으면 1을(즉, lastNameA를 lastNameB보다 뒤에 오도록) 반환하도록 한다.

7) Sum up the instances of each of these: 각 instance 별로 개수의 합계를 계산하라.

const data = [
        "car",
        "car",
        "truck",
        "truck",
        "bike",
        "walk",
        "car",
        "van",
        "bike",
        "walk",
        "car",
        "van",
        "car",
        "truck",
];

const all = data.reduce(function (allTrans, trans) {
        if (trans in allTrans) {
          allTrans[trans] += 1;
        } else {
          allTrans[trans] = 1;
        }
        return allTrans;
}, {});

console.table(all);
  • reduce() 메소드의 initialValue는 빈 객체 {}이다. 만약 trans, 즉 "car", "truck" 등 data 배열의 요소들 중 하나가 객체에 있으면, 객체 내의 해당 key의 value 값에 1을 더한다. 그리고 만약 객체에 없으면 해당 trans를 key로 갖는 element를 생성한 뒤, 1을 할당한다.

참고

profile
say hi to the world

0개의 댓글