• Array.prototype.filter()
  • Array.prototype.map()
  • Array.prototype.sort()
  • Array.prototype.reduce()

Array.prototype.filter()

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

callback 테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 통과하지 못했으면 빈 배열을 반환합니다.

    const fifteen = inventors.filter(function(inventor) {
        if(inventor.year >= 1500 && inventor.year < 1600) {
            return true; // keep it!
        }
    })
console.table(fifteen);
const fifteen2 = Inventors.filter(inventor => (inventor.year >= 1500 && inventor.year < 1600))

It’s same

Array.prototype.map()

똑같은 길이의 array 반환

공장에서 스탬프를 찍는 것과 똑같다.

const fullName = Inventors.map(Inventor => Inventor.first + " " + Inventor.last);
const fullName2 = Inventors.map(Inventor => `${Inventor.first} ${Inventor.last}`);

Array.prototype.sort()

정렬 방식,

const ordered = Inventors.sort(function(firstPerson, secondPerson) {
    if(firstPerson.year > secondPerson.year) {
        return 1;
    } else {
        return -1;
    }
})

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 = category.querySelectorAll('a');

querySelector는 Nodelist 반환!

const links = Array.from(category.querySelectorAll('a'));
const links = [...category.querySelectorAll('a')];
const de = links
            .map(link => link.textContent)
            .filter(streetName => streetName.includes('de'));
console.log(de);

7. Sort Exercise

const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black, Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William'];
const alpha = people.sort(function(lastOne, nextOne) {
    const [aLast, aFirst] = lastOne.split(', ')
    const [bLast, bFrst] = nextOne.split(', ')
    return aLast > bLast ? -1 : 1
})
// 오름차순 sort

8. Reduce Exercise

most flexible function

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

const transportation = data.reduce(function(obj, item) {
    if(!obj[item]) {
        obj[item] = 0;
    }
    obj[item]++;
    return obj;
}, {})

댓글남기기