자바스크립트 sort()로직

2023. 4. 15. 11:40·javascript

Array.prototype.sort()

배열을 정렬하는 메소드.

기본 정렬 순서는 문자열 유니코드를 기준으로 한다. 

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]

 

반환값은 새로운배열이 만들어지는게 아니라 원배열이 수정된다. 

 

정렬기준을 매개변수로 받아서 구현할 수 있다. 

 arr.sort([compareFunction])

 

숫자를 비교해서 정렬하는 compareFunction

(Infinity 및 NaN이 포함되어 있지 않은 경우)

let test = [1, 2, 3, 4, 11];

function compareNumbers(a, b) {
  return a - b;
}

test.sort(compareNumbers);
// 결과 [1, 2, 3, 4, 11]

 

sort 메소드는 함수식과 함께 편하게 사용할 수도 있다. 

var numbers = [1, 2, 3, 4, 11];
numbers.sort(function(a, b) {
  return a - b;
});
// 결과 [1, 2, 3, 4, 11]

 

객체 정렬하기 

객체 특정값 (value값으로 정렬하기)

var items = [
  { name: 'seonji', value: 13 },
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// value 기준으로 정렬
items.sort(function (a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  // a must be equal to b
  return 0;
});

/*
결과
[
  {name: 'The', value: -12}, 
  {name: 'seonji', value: 13},
  {name: 'Magnetic', value: 13},
  {name: 'Edward', value: 21},
  {name: 'Sharpe', value: 37},
  {name: 'Zeros', value: 37},
  {name: 'And', value: 45}
]
*/

 

객체 name값으로 정렬하기 

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// name 기준으로 정렬
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA > nameB) {
    return 1;
  }
  if (nameA < nameB) {
    return -1;
  }

  // 이름이 같을 경우
  return 0;
});

/*
결과
[
  {name: 'And', value: 45}, 
  {name: 'Edward', value: 21}, 
  {name: 'Magnetic', value: 13},
  {name: 'Sharpe', value: 37},
  {name: 'The', value: -12},
  {name: 'Zeros', value: 37},
]
*/

 

참고 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#%EB%A7%A4%EA%B0%9C%EB%B3%80%EC%88%98

'javascript' 카테고리의 다른 글

Array.prototype.reduce()  (0) 2023.04.20
call, bind, apply의 this binding  (0) 2023.04.19
fetch() error 처리하기  (0) 2023.03.17
parseInt(), Number() 의 차이  (0) 2023.03.02
Array.findIndex()  (0) 2023.03.02
'javascript' 카테고리의 다른 글
  • Array.prototype.reduce()
  • call, bind, apply의 this binding
  • fetch() error 처리하기
  • parseInt(), Number() 의 차이
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • TECH (82)
      • Next.js (8)
      • React (25)
      • Vite (1)
      • javascript (17)
      • CSS (6)
      • CS (10)
      • AWS (0)
      • Jest (1)
      • CI|CD (0)
      • 알고리즘 (8)
      • Tools (1)
      • Tips (5)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      redux
      reat-head
      react state management
      theme-provider
      함수와 메서드차이
      styled-components
      call signatures
      타입스크립트
      웹브라우저구성
      JavaScript
      nextjs
      app-router
      global-style
      git배포
      배열요소순서
      Array.sort()
      TypeScript
      서버컴포넌트
      React
      커머스프로젝트
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    ssund
    자바스크립트 sort()로직
    상단으로

    티스토리툴바