1. Array.filter()
const born = inventors.filter(inventor => 1500 <= inventor.year && inventor.year < 1600);
console.log(born);
inventors를 하나하나 돌며 inventor를 얻고 이를 filter함수로 대 소 비교하여 born에 저장 함
- filter() : arr.filter(callback(element[, index[, array]])[, thisArg]) filter() 안에 함수를 넣을 수 있고 function에 조건에 맞는 요소들을 모아 다시 array로 반환해 줌 map과 다른 점은 오직 함수 조건에 따른 true/false로 나뉘어 조건에 맞는 걸 반환하는 것
2. Array.map()
const fullname = inventors.map(inventor => inventor.first + inventor.last);
console.log(fullname);
console.table(fullname);
dict 형태로 저장된 inventor 안에서 firstname과 lastname을 뽑아낸다
- map() : arr.map(callback(currentValue[, index[, array]])[, thisArg]) filter와 유사하게 함수를 이용하지만 filter와 다른 점은 함수를 적용한 결과값을 모아 새로운 배열을 반환 한다는 점임(데이터가 바뀜)
3. sort
const oldered = inventors.sort(function(a, b) {
if(a.year>b.year) {
return 1; // 앞에 위치
} else {
return -1; // 뒤에 위치
}
});
console.table(oldered);
return 값을 반대로 하면 내림차순으로 정렬 됨
- sort() : arr.sort([compareFunction])
- year의 값을 compare function을 통해 정렬, compare function이 없으면 요소를 문자열로 변환하고 유니코드 순서로 비교해 정렬된다
4. Array.reduce()
const totalYear = inventors.reduce((total, inventor) => {
return total + (inventor.passed - inventor.year);
}, 0);
console.log(totalYear);
모든 inventor들 의 나이 총 합을 구함
- reduce(): arr.reduce(callback[, initialValue]) 콜백 함수의 반환 값들을 하나의 값(acc)에 누적 후 반환
5. sort 2
const oldest = inventors.sort(function (a, b) {
const lastGuy = a.passed - a.year
const nextGuy = b.passed - b.year
return lastGuy > nextGuy ? -1: 1;
// if (lastGuy > nextGuy) {
// return -1;
// } else {
// return 1;
// }
});
console.table(oldest)
오래 살았던 사람 순으로 내림차순
주석 처리된 부분은 shorthand 되지 않은 if~else문
6. find keyword in Html element
7. sort 3 (alphabetically sort)
const alpha = people.sort(function (lastOne, nextOne) {
const [aLast, aFirst] = lastOne.split(', ');
const [bLast, bFirst] = nextOne.split(', ');
return aLast > bLast ? 1: -1;
});
console.log(alpha);
last name을 알파벳 사전 순으로 정렬
정렬할 Array의 기존 형태 이름이 'Bernhard, Sandra', 형식으로 되어 있었기 때문에 ,(공백) 을 기준으로 split하여 이름을 나누어 줌
8. Array.reduce() 로 개수 세기
const data = ['car', 'car', 'truck', 'truck', 'bike',
'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const test = data.reduce(function (obj, item) {
obj[item]++;
return obj
}, {
car: 0,
truck: 0,
bike: 0,
walk: 0,
van: 0,
});
console.log(test)
const transportation = data.reduce(function (obj, item) {
if(!obj[item]) {
obj[item] = 0;
}
obj[item]++;
return obj;
}, {});
console.log(transportation)
test code와 transportation의 결과는 같음
우리는 car: 0 형식으로 출력 할 것이기 때문에 {} 영역이 2개 필요하고 숫자를 세 줄 영역을 적어줌
transportation은 if구문을 사용하여 기본 옵션을 적어주기 때문에 {} 영역에 따로 정의해줄 필요 없음
만약 기본 값을 적어주지 않는다면 없는 object인 NaN이 출력 됨
'DEV > JS30' 카테고리의 다른 글
[JS30] day 6 - Ajax type ahead (0) | 2021.12.12 |
---|---|
[JS30] day 5 - Flex panels image gallery (0) | 2021.12.09 |
[JS30] day 3 - playing with CSS variables and JS (0) | 2021.12.07 |
[JS30] day 2 - CSS Clock (0) | 2021.12.06 |
[JS30] day 1 - drumkit (0) | 2021.12.05 |