포시코딩

Array.sort() 배열 내 오브젝트 값으로 정렬하기 본문

JavaScript

Array.sort() 배열 내 오브젝트 값으로 정렬하기

포시 2022. 7. 8. 13:08
728x90
let data = [
    {
      id : 0,
      title : "White and Black",
      content : "Born in France",
      price : 120000
    },
    {
      id : 1,
      title : "Red Knit",
      content : "Born in Seoul",
      price : 110000
    },
    {
      id : 2,
      title : "Grey Yordan",
      content : "Born in the States",
      price : 130000
    }
  ];

위 data 라는 Array 안에 있는 오브젝트들을 title 로 정렬하고 싶은 경우

data.sort(function(a, b){
    if(a.title < b.title){
        return -1;
    }
    if(a.title > b.title){
        return 1;
    }
    return 0;
});
console.log(data);

G -> R -> W 
순으로 정렬이 되었다!

나중에 이름순으로 정렬, 날짜순으로 정렬 등의 버튼에 쓸 수 있을거 같다.

728x90

'JavaScript' 카테고리의 다른 글

Promise, async/await을 통한 순차실행 - 작성중  (0) 2022.12.03
클립보드에 복사  (0) 2022.11.09
script 파일 불러올 때 쓰는 defer가 뭘까? (async, defer)  (0) 2022.10.19
Array.prototype.find()  (0) 2022.07.08
Promise 예제  (0) 2022.06.18