1. Array APIs
배열의 API들을 연습하기 위한 문제들이다.
<script>
// Get your shorts on - this is an array workout!
// ## Array Cardio Day 1
// Some data we can work with
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 people = [
'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig',
'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter', 'Benjamin, Walter', 'Berlin, Irving',
'Benn, Tony', 'Benson, Leana', 'Bent, Silas', 'Berle, Milton', 'Berry, Halle', 'Biko, Steve', 'Beck, Glenn', 'Bergman, Ingmar', 'Black, Elk', 'Berio, Luciano',
'Berne, Eric', 'Berra, Yogi', 'Berry, Wendell', 'Bevan, Aneurin', 'Ben-Gurion, David', 'Bevel, Ken', 'Biden, Joseph', 'Bennington, Chester', 'Bierce, Ambrose',
'Billings, Josh', 'Birrell, Augustine', 'Blair, Tony', 'Beecher, Henry', 'Biondo, Frank'
];
// Array.prototype.filter()
// 1. Filter the list of inventors for those who were born in the 1500's
const fifteens = inventors.filter(inventor => inventor.year < 1600 && inventor.year >= 1500);
console.table(fifteens);
// Array.prototype.map()
// 2. Give us an array of the inventors first and last names
const firstNames = inventors.map(inventor => inventor.first);
const lastNames = inventors.map(inventor => inventor.last);
console.log(firstNames);
console.log(lastNames);
// Array.prototype.sort()
// 3. Sort the inventors by birthdate, oldest to youngest
const oldToYoung = inventors.sort(function compare (old, young) {
return old.year - young.year;
});
console.table(oldToYoung);
console.log(inventors);
// real answer
const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1);
console.table(ordered);
// Array.prototype.reduce()
// 4. How many years did all the inventors live all together?
function liveAllTogether () {
const maxYear = inventors.reduce(function compare (old, young) {
if (old.year - young.year < 0) {
return young;
} else if (old.year - young.year > 0) {
return old;
} else {
return old;
}
});
console.log(maxYear);
const minPassed = inventors.reduce(function compare (old, young) {
if (old.passed - young.passed < 0) {
return old;
} else if (old.passed - young.passed > 0) {
return young;
} else {
return old;
}
});
console.log(minPassed);
if (maxYear - minPassed < 0 ) {
return console.log(minPassed - maxYear + 1);
} else if (maxYear - minPassed == 0) {
return console.log(1);
} else {
return console.log(0);
}
}
liveAllTogether();
// real answer
const totalYears = inventors.reduce((total, inventor) => {
return total + (inventor.passed - inventor.year);
}, 0);
console.log(totalYears);
// 5. Sort the inventors by years lived
const livedYears = inventors.sort(function compare (a, b) {
return (a.passed - a.year) - (b.passed - b.year);
});
console.table(livedYears);
// 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
// https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
const category = document.querySelector('.mw-category');
const links = Array.from(category.querySelectorAll('a'));
const de = links
.map(link => link.textContent)
.filter(streetName => streetName.includes('de'));
// 7. sort Exercise
// Sort the people alphabetically by last name
const alpha = people.sort(function (lastOne, nextOne) {
const [aLast, aFirst] = lastOne.split(', ');
const [bLast, bFirst] = nextOne.split(', ');
return aLast > bLast ? 1 : -1;
});
console.table(alpha);
// 8. Reduce Exercise
// Sum up the instances of each of these
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const transportaion = data.reduce(function (obj, item) {
if (!obj[item]) {
obj[item] = 0;
}
obj[item]++;
return obj;
}, {})
console.log(transportaion);
</script>
1) Filter the list of inventors for those who were born in the 1500's
- 1500년대에 태어난 inventors들을 걸러내기 위해 filter API를 사용했다. filter는 배열의 모든 요소들 중, 괄호 안의 조건을 통과하는 요소만을 모은 배열을 반환한다. inventor의 출생년도(year)가 1500과 1600 사이에 있으면 된다. console.table로 조금 더 보기 쉽게 나타냈다.
2) Give us an array of the inventors first and last names
- inventors의 성과 이름을 각각 모으기 위해, map API를 이용했다. map은 배열 내의 모든 요소에 대하여 각각 주어진 콜백함수를 호출한 결과를 모아 새로운 배열을 반환한다. 그러므로 inventors 배열의 first, last 키의 value만을 모은 배열을 반환하도록 firstNames, lastNames라는 변수를 각각 정의하였다.
3) Sort the inventors by birthdate, oldest to youngest
- 나이가 많은 순으로 정렬, 즉 출생 년도가 빠른 사람 순으로 정렬하기 위해 sort API를 이용했다. sort는 매개변수를 할당하지 않으면 요소를 문자열로 변환하여 유니코드 포인트 순서대로 정렬한다. 이 경우, 숫자도 모두 문자열로 변환되므로 10이 2보다 앞에 오게 된다.
- 매개변수로 compareFunction(old, young)를 할당하는 경우, 그 반환 값이 0보다 작으면 old가 young보다 낮은 색인이 되어 앞에 정렬된다.
- 정렬 기준에 따라서 기존의 배열이 변형된다. 기존 배열이 변형되었기 때문에, console.log(inventors)를 다시 실행하더라도 변형된 순서의 배열이 반환된다.
※ number, string, boolean, undefined, null, symbol과 같은 원시타입 데이터를 변수로 정의할 때에는, 데이터가 메모리에 적재된다. 원시타입이 아닌 array, object를 변수로 정의할 때에는, 메모리에 데이터 자체를 저장하지 않고, 포인터를 저장하여 해당 array나 object를 참조하도록 한다. 위 코드에서, oldToYoung는 inventors와 같은 포인터를 가지기 때문에, console.log(inventors)를 oldToYoung의 정의보다 위에서 실행해도 여전히 변형된 순서의 배열을 반환한다.
4) How many years did all the inventors live all together?
- 모든 inventors가 함께 살았던 햇수는 얼마나 되는지 확인해야 한다. 가장 늦게 태어난 사람이 가장 빨리 죽은 사람과 함께 살았던 햇수가 그 답이 될 것이다. 그러므로 가장 늦게 태어난 사람의 출생년도인 year의 최댓값과 가장 빨리 죽은 사람의 사망년도인 passed의 최솟값을 비교하여, maxYear - minPassed < 0인 경우 그 차이가 함께 살았던 햇수가 될 것이다. year의 최댓값과 passed의 최솟값을 구하기 위해 reduce API를 이용하였다.
- reduce API는 배열의 모든 요소에 콜백함수를 실행한다. 이 때, 실행한 콜백함수의 반환값이 다음 실행에 반영된다. 이를테면, 위 코드에서, old와 young 두 변수를 사용한 reduce의 첫 번째 실행에서, old가 반환되었고, 그 값이
Albert라고 하자. 이 경우에, 반환된 old인 Albert는, 두 번째 실행에서도 다시 사용되어 다른 값과의 비교를 시작할 것이다.
5) Sort the inventors by years lived
- 연령순서대로 정렬하기 위해, sort API를 이용해 passed - year이 큰 순서대로 정렬했다.
6) create a list of Boulevards in Paris that contain 'de' anywhere in the name
- 해당 웹페이지에서 개발자 도구를 이용해 도시의 리스트를 나타내는 태그가 무엇인지 찾는다. 'mw-category' 클래스가 도시의 리스트를 나타내고 있으므로, querySelector로 해당 클래스를 선택하여 category 변수에 할당한다. 또, category 안에, 실제로 문자열이 쓰여진 태그는 a태그이므로, querySelectorAll을 이용해 모든 a태그를 선택한다. 이를 통해 반환되는 것은 Nodelist이므로, Array.from() 매소드를 통해 배열로 변환하고, links 변수에 할당한다.
- links를 console.log로 확인해 보면, a로 구성된 배열이 나타난다. map과 textContent 속성을 사용해 이를 텍스트로 변환해 준 뒤, filter와 includes를 통해 문자열 de를 포함하는 요소만을 반환한다. includes는 배열이 특정 요소를 포함하고 있는지를 판별한다.
7) Sort the people alphabetically by last name
- sort를 통해 알파벳 순서대로 정렬하고자 한다. 매개변수 lastOne은, split을 통해 콤마(,)를 기준으로 성과 이름으로 나누고, 이를 aLast, aFirst에 각각 구조 분해 할당한다. nextOne도 동일하게 구조 분해 할당하여 bLast, bFirst에 할당한다.
- 구조 분해 할당은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 표현식이다.
- 이렇게 할당된 aLast와 bLast의 값을 비교하여 알파벳 순으로 정렬한다.
8) Sum up the instances of each of these
- 각 교통수단이 몇 개 있는지 파악하기 위해, 축적된 값을 표시할 수 있는 reduce를 사용한다. obj 객체에 값을 축적시킬 수 있도록 콜백함수의 첫 번째 매개변수로 지정하고, reduce의 두 번째 매개변수에 빈 객체를 할당하여 obj를 초기화한다.
- computed property는 대괄호를 이용해 어떤 key 값을 불러올지 알 수 없는 경우에 사용하는데, 여기에서는 어떤 교통수단이 있을지 직접 확인하지 않고 계산된 프로퍼티를 이용해 객체의 key 값을 받아 올 것이다. obj[item]이 존재하지 않는 경우에는 item을 key로, 0을 value로 가지고, 존재하는 경우에는 value에 1을 더하여 obj를 반환하도록 하였다. data의 모든 요소에 대하여 이를 실행하므로, 교통수단: 갯수를 key: value로 가지게 된다.
- 객체에 속성을 추가하는 형태는 두 가지가 있다. Object.property = value, Object[property] = value인데, 첫 번째는 코딩 시점에서 추가할 때 사용하고, 두 번째는 실시간으로 값을 받아오는 경우에 사용한다.
[Javascript] 06. Ajax Type Ahead (0) | 2021.04.17 |
---|---|
[Javascript] 05. Flex Panel Gallery (0) | 2021.04.16 |
[Javascript] 03. Update CSS Variables with JS (0) | 2021.04.14 |
[Javascript] 02. CSS + JS Clock (0) | 2021.04.12 |
[Javascript] 01. Drum Kit (0) | 2021.04.12 |
댓글 영역