JavaScript

객체 정렬하기

수연 (Suyeon) 2022. 12. 1. 23:57
반응형

쇼핑몰을 만들려고 할 때 꼭 있어야 하는 가격 정렬, 상품명 정렬 등.. 이런 기능이 필요합니다.

 

1. 상품명으로 정렬하기

let goods = [
  {
    name: 'Pink cote',
    cost: 34000
  },
  {
    name: 'Blue cote',
    cost: 54000
  },
  {
    name: 'Orange cote',
    cost: 72000
  },
];

// 상품명으로 오름차순 정렬
// 원본은 유지하기.
let copyGoods = [...goods];
copyGoods.sort((item1, item2) => {
  return item1.title > item2.title ? 1 : -1;
});

// 상품명으로 내림차순 정렬
copyGoods.sort((item1, item2) => {
  return item1.title > item2.title ? -1 : 1;
});

원본을 유지하는 이유는 필터 적용을 해제했을 때 원래대로 돌아와야 하기 때문입니다.

 

2. 상품 가격으로 정렬하기

let goods = [
  {
    name: 'Pink cote',
    cost: 34000
  },
  {
    name: 'Blue cote',
    cost: 54000
  },
  {
    name: 'Orange cote',
    cost: 72000
  },
];

// 상품 가격으로 오름차순 정렬
// 원본은 유지하기.
let copyGoods = [...goods];
copyGoods.sort((item1, item2) => {
  return item1.cost > item2.cost ? 1 : -1;
});

// 상품 가격으로 내림차순 정렬
copyGoods.sort((item1, item2) => {
  return item1.cost > item2.cost ? -1 : 1;
});
728x90

'JavaScript' 카테고리의 다른 글

reduce와 concat 활용하기  (0) 2023.02.02
this란 무엇인가  (0) 2022.12.06
가변 객체와 불변 객체  (0) 2022.11.30
자바스크립트 데이터 타입  (0) 2022.11.28
백준 입출력 문제 풀기  (0) 2022.11.25