[JS] Array 배열 group별로 묶는 방법

2024. 8. 21. 00:13·Frontend/JavaScript & Jquery
const array = [
  {
    id: 1,
    type: "사과",
    dueDate: "20241215",
    price: 11369,
  },
  {
    id: 2,
    type: "바나나",
    dueDate: "20241215",
    price: 19194,
  },
  {
    id: 3,
    type: "사과",
    dueDate: "20241215",
    price: 9010,
  },
  {
    id: 4,
    type: "사과",
    dueDate: "20241208",
    price: 19517,
  },
  {
    id: 5,
    type: "바나나",
    dueDate: "20241208",
    price: 18910,
  },
  {
    id: 6,
    type: "바나나",
    dueDate: "20241208",
    price: 3936,
  },
  {
    id: 7,
    type: "키위",
    dueDate: "20240927",
    price: 13938,
  },
  {
    id: 8,
    type: "키위",
    dueDate: "20240927",
    price: 4495,
  },
  {
    id: 9,
    type: "배",
    dueDate: "20240927",
    price: 16801,
  },
  {
    id: 10,
    type: "배",
    dueDate: "20240927",
    price: 12689,
  },
];

const array2 = [
  {
    id: 11,
    type: "사과",
    dueDate: "20240927",
    price: 20000,
  },
  {
    id: 12,
    type: "바나나",
    dueDate: "20240927",
    price: 34000,
  },
  {
    id: 13,
    type: "키위",
    dueDate: "20240209",
    price: 2090,
  },
  {
    id: 14,
    type: "배",
    dueDate: "20240209",
    price: 4900,
  },
];

이런 array를 type을 이용해 묶고 싶다.

 

이런식으로 

 

const groupBy = array.reduce((acc, item) => {
  const { type, dueDate } = item;
  acc[type] = acc[type] || [];
  acc[type].push({ ...item });
  return acc;
}, {});

 

array2도 추가로 합치고 싶을 때는?

const groupBy2 = array2.reduce((acc, item) => {
  const { type, dueDate } = item;
  acc[type] = acc[type] || [];
  acc[type].push({ ...item });
  return acc;
}, {});

const mergeObjects = (obj1, obj2) => {
  const result = { ...obj1 };

  Object.keys(obj2).forEach((key) => {
    if (Array.isArray(obj2[key]) && Array.isArray(obj1[key])) {
      result[key] = [...obj1[key], ...obj2[key]];
    } else {
      result[key] = obj2[key];
    }
  });

  return result;
};

console.log(mergeObjects(groupBy, groupBy2));

 

groupBy 변수는 함수로 만들 수 있을 것 같다.

function groupBySomething(array, something) {
  return array.reduce((acc, item) => {
    const groupKey = item[something]; // key에 따라 그룹화 기준을 설정
    acc[groupKey] = acc[groupKey] || [];
    acc[groupKey].push({ ...item });
    return acc;
  }, {});
}

// 타입으로 그룹을 묶을 수 있고
console.log(
  'groupBySomething(array, "type"): ',
  groupBySomething(array, "type"),
);

// dueDate로 그룹을 묶을 수 있다
console.log(
  'groupBySomething(array, "dueDate"): ',
  groupBySomething(array, "dueDate"),
);

 

 

반응형
저작자표시 (새창열림)

'Frontend > JavaScript & Jquery' 카테고리의 다른 글

JavaScript 단축 속성명 & 속성 계산명  (0) 2025.01.07
JS 조건문 break와 continue에 대해서  (1) 2024.12.09
[JS 문법] call, apply, bind 메소드로 this 명시적 바인딩하기  (0) 2024.07.14
[JS 문법] this 바인딩에 대해서  (2) 2024.07.14
[JS 문법] JS 호이스팅에 대해서  (0) 2024.07.14
'Frontend/JavaScript & Jquery' 카테고리의 다른 글
  • JavaScript 단축 속성명 & 속성 계산명
  • JS 조건문 break와 continue에 대해서
  • [JS 문법] call, apply, bind 메소드로 this 명시적 바인딩하기
  • [JS 문법] this 바인딩에 대해서
전예방
전예방
  • 전예방
    예방이의 개발일기
    전예방
  • 전체
    오늘
    어제
    • All (125)
      • Info & Tip (2)
      • 유용한 사이트들 (5)
      • Mark Up & StyleSheet (23)
        • HTML (6)
        • CSS & SCSS (10)
        • 반응형 (6)
      • Frontend (66)
        • 전체 (10)
        • JavaScript & Jquery (18)
        • TypeScript (0)
        • React (26)
        • Next.js (3)
        • 성능최적화 (2)
        • 웹접근성 (2)
      • Backend (13)
        • Python (1)
        • JAVA (2)
        • node.js (0)
        • PHP (7)
        • 패키지매니저 (3)
      • Markdown (0)
      • SCM (1)
        • Git&Github (1)
        • SVN (0)
      • IDE (4)
        • VSCode (2)
        • IntelliJ (1)
        • Ecplise (1)
      • 취미생활 (3)
      • 정보처리기사 (2)
      • 코딩자율학습단 (5)
        • 12기 (파이썬) (5)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

    • velog
    • github
  • 공지사항

  • 인기 글

  • 태그

    react
    React Swiper
    frontend
    Python
    파이썬
    NPM
    TypeScript
    코딩자율학습단
    yarn berry
    반응형
    회원가입
    php
    swiper.js
    나도코딩
    관리자 페이지
    코딩자율학습
    리액트
    Admin
    Chart.js
    CSS
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.3
전예방
[JS] Array 배열 group별로 묶는 방법
상단으로

티스토리툴바