Javascript

Array.sort

MuGrammer 2019. 5. 8. 14:47
array.sort([compareFunction])

array.sort(function(nextIndexValue, currentIndexValue){
	.. compare nextIndexValue to currentIndexValue..
    return 0 or 1 or -1
})

 

1. array.sort() 

   - compareFuntion이 지정되어 있지 않으면 각 요소들을 문자열로 변환 후 유니코드 포인트 순서로 문자열을 정렬한다. 

   - 기본 오름차순

   ※ 문자열로 변환 후 값을 비교하게 되므로 9, 80은 "9", "80"으로 변경되어 "80", "9" 순으로 정렬되어진다. 

 

2. array.sort(compareFuntion)

   - paremeter로 2개의 배열의 값을 가져오게된다. 

   - 첫번째 인자는 현재 index의 값, 두번째 인자는 현재 index의 값

 

   - return 0 : 값이 동일하거나 변경이 필요없을 경우

   - return 1 : nextIndexValue의 값이 currentIndexValue보다 클 경우 (내림차순)

   - return -1 : nextIndexValue의 값이 currentIndexValue보다 작을 경우 (오름차순)

 

 

개인적으로 위 기능은 테이블 내용을 정렬할 때 유용하게 사용하고 있다. 

 

필수적으로 compareFunction을 작성해서 $.isNumeric 함수를 사용해서 숫자와 문자열 정렬을 구분하는 과정이 필요하다. 

 

 

참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

반응형

'Javascript' 카테고리의 다른 글

Table - td index 설정  (0) 2020.09.22
Image Lazy Loading  (0) 2019.10.04
Eclipse - Emmet (Zen Coding) Plugin 추가  (1) 2018.07.23
[Jquery] click 이벤트 활성화, 비활성화  (1) 2015.03.05
동적테이블 생성  (0) 2015.01.20