반응형

여러가지 배열 연산 형태 
함수 형태나 쓰임이 많다보니 코드를 봤을때 대체 무슨 의미인지 파악이 어려워서 공부하다가 형태를 기억하면 좋을것 같아서 남겨놔봤다. 

type Book = {
    title: string;
    copyright?: string;
    author?: string;
};

const books: string[] = [
    "헨리 6세",
    "리처드 3세",
    "실수 연발",
    "말괄량이 길들이기",
    "헨리 8세",
];

// foreach 문
books.forEach((book: string, idx: number, books: string[]) => {
    console.log(book, idx);
})

// map 사용1
const bookObject: Book[] = books.map((book:string) =>{
    return {
        title:book,
        author: undefined,
    };
});

console.log(bookObject); 
/*  [ { author: undefined, title: '헨리 6세' },
  { author: undefined, title: '리처드 3세' },
  { author: undefined, title: '실수 연발' },
  { author: undefined, title: '말괄량이 길들이기' },
  { author: undefined, title: '헨리 8세' } ] */

// map 사용2
const ShakespeareOneBooks: Book[] = books.map((book: string) => ({
    title:book
}))
.map((book: Book) => ({
    ...book,
    author: "William Shakespeare"
}));

console.log(ShakespeareOneBooks);

// map 사용2 와 형태가 다르지만 동일 동작임.
const bookTitleToBookObject = (book: string) => ({title:book});
const makeAuthor = (name: string) => (book: Book) => ({
    ...book,
    author: name
});

const shakespeareTwoBooks: Book[] = books
.map(bookTitleToBookObject)
.map(makeAuthor("William Shakespeare"));

console.log(shakespeareTwoBooks);

// filter
const henry: Book[] = shakespeareTwoBooks.filter((book: Book) =>
    book.title.includes("헨리")
);

console.log(henry);

// reduce
// reduce 는 함수와 초기화 값을 넘겨줌
// 함수에는 2개의 인자를 넘겨주는데 첫번째에는 초기값, 두번째는 배열의 값을 넘겨줌
// 함수가 반복되면서 첫번째 인자에는 다시 결과값을 계속 넣어주게됨.
// 0, 10 -> 10, 5 -> 15, 3 .. 이런 형태로 값이 들어감.
const someNumbers: number[] = [10,5,3,14,56];
const someNumber = someNumbers.reduce((a:number, b:number) => a + b , 0)

console.log(someNumber);	// 88

type SomeObject = {
    [key: string]: string | number;
};

// reduce object
const someObjects: SomeObject[] = [
    { border: "none"},
    { fontSize: 24},
    {className: "box sm-box"},
];

const someObject: SomeObject = someObjects.reduce(
    (a: SomeObject, b: SomeObject) => ({...a, ...b}),
    {}
);
console.log(someObject) // { border: 'none', className: 'box sm-box', fontSize: 24}

(출처 : 패스트 캠퍼스 - 김민태의 프론트엔드 아카데미 : https://fastcampus.co.kr/dev_academy_kmt1)

728x90
반응형

+ Recent posts