Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Archives
Today
Total
관리 메뉴

쩡이 개발공부 블로그

reduce 사용하기 본문

공부

reduce 사용하기

쪙잉ㅇ 2023. 9. 10. 23:36

어떤 함수를 실행시킨 결과를 보내야 하는데, 큐가 받는 형식에 맞게 수정을 해서 보내야 한다.

 

함수 실행 결과는 아래처럼 나온다. 

{
	productNo : number;
    Items : ItemModel[];
    start: string;
    end: string;
    execTime: string;
}

여기서 같은 productNo를 가진 아이템들을 합치고, 시작 시간과 종료 시간을 비교해서 넣어줘야 한다. 

 

이제 reduce를 사용해 acc 배열 순회하면서 중복 productNo를 가진 항목들을 병합하여 최종 데이터를 생성한다. 

const Data = messageList.reduce((acc, item) => {
    let isEdit = false;
    for (let i = 0; i < acc.length; i++) {

        if (acc[i].productNo == item.productNo) {
            acc[i].item.push(...item.items);

            if (new Date(acc[i].start) > new Date(item.start)) {
                acc[i].start = item.start;
            }

            if (new Date(acc[i].end) < new Date(item.end)) {
                acc[i].end = item.end;
            }

            isEdit = true;
        }
    }

    if (!isEdit) {
        acc.push(item);
    }

    return acc;
}, []);

 

정말이지 자료구조는 너무 어렵다. 

'공부' 카테고리의 다른 글

useRef로 스크롤 이동시키기  (5) 2023.10.22
클린 아키텍처  (8) 2023.10.15
git push 되돌리기  (5) 2023.10.09
Swiper 슬라이드 사용해보기  (3) 2023.09.17
React 상태관리 MobX  (5) 2023.09.03
Comments