Javascript 배열 정렬하는 방법 sort()

Progmming/Javascript|2018. 12. 17. 14:13
반응형

Javascript 배열 정렬 샘플 코드 



기본 사용법 


Sorting ascending // 오름차순 정렬

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
for(i=0;i<points.length;i++)
{
	document.write(points[i]+",");
}
</script>


 Sorting descending // 내림차순 청렬

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});

for(i=0;i<points.length;i++)
{
	document.write(points[i]+",");
}
</script>



적용 샘플

<!doctype html> <html lang="en"> <head> <script src="//code.jquery.com/jquery-1.7.2.js"></script> </head> <body> <h1>DIV sorting</h1> <input type="button" value="Add" id="btnAdd" /> <div id="starting_divs"> <div class="item" data-order="100"> <table> <tr> <td>STD</td> <td>100</td> </tr> </table> </div> <div class="item" data-order="50"> <table> <tr> <td>STD</td> <td>50</td> </tr> </table> </div> <div class="item" data-order="500"> <table> <tr> <td>STD</td> <td>500</td> </tr> </table> </div> <div class="item" data-order="150"> <table> <tr> <td>STD</td> <td>150</td> </tr> </table> </div> </div> <script type="text/javascript"> function fnSort() { var $sorted_items, getSorted = function(selector, attrName) {                          return $( $(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; }) ); }; $sorted_items = getSorted('#starting_divs .item', 'data-order').clone(); $('#starting_divs').html( $sorted_items ); } $("#btnAdd").on("click",function(){ var order = (Math.random()*10000).toString().substring(0,3); $("<div class=\"item\" data-order=\""+order+"\"> \ <table><tr><td>DLX</td><td>"+order+"</td></tr></table> \ </div>").insertAfter(".item:last"); fnSort(); }); </script> </body> </html>


데이터형에 따라서 문자열일 경우 비교/리턴 하는부분에서 아래와 같이 변경한다.

<script>
return $(
	$(selector).toArray().sort(function(a, b){
		var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
		return aVal.localeCompare(bVal);
	})
</script>


복합 정렬일 경우 아래와 같이 || 조건으로 비교한다.

<script> return $( $(selector).toArray().sort(function(a, b){ var aint = parseInt(a.getAttribute('sort-int')), bint = parseInt(b.getAttribute('sort-int')), aName = a.getAttribute('sort-name'), bName = b.getAttribute('sort-name'); return aint - bint || aName.localeCompare(bName); }) ); </script>


w3schools Link : https://www.w3schools.com/js/js_array_sort.asp



최종 사용하려고 했던 함수.

<script type="text/javascript">

	function fnSort(sortBy)
	{
 
		$(".btn.btn-white").removeClass("active");

		var $sorted_items,
			getSorted = function(selector) {
				switch(sortBy){
					case "AVAILABLE" :
						$(".btn.btn-white").eq(1).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aStatus = a.getAttribute('sort-status'),
								bStatus = b.getAttribute('sort-status'),
								aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aStatus.localeCompare(bStatus) || aPrice - bPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "PRICE" :
					case "LOWPRICE" :
						$(".btn.btn-white").eq(2).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aPrice - bPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "HIGHPRICE" :
						$(".btn.btn-white").eq(3).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aPrice = parseInt(a.getAttribute('sort-price')),
								bPrice = parseInt(b.getAttribute('sort-price')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return bPrice - aPrice || aName.localeCompare(bName);
							})
						);
						break;
					case "RATING" :
					case "GRADE" :
						$(".btn.btn-white").eq(4).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aGrade = parseInt(a.getAttribute('sort-grade')),
								bGrade = parseInt(b.getAttribute('sort-grade')),
								aName = a.getAttribute('sort-name'),
								bName = b.getAttribute('sort-name');
								return aGrade - bGrade || aName.localeCompare(bName);
							})
						);
						break;
					case "HENM" :
						$(".btn.btn-white").eq(5).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
								return aVal.localeCompare(bVal);
							})
						);
						break;
					default :
						$(".btn.btn-white").eq(5).addClass("active");
						return $(
							$(selector).toArray().sort(function(a, b){
								var aVal = a.getAttribute('sort-name'), bVal = b.getAttribute('sort-name');
								return aVal.localeCompare(bVal);
							})
						);
						break;
				}
			};

		$sorted_items = getSorted('#starting_divs .item').clone();

		$('#starting_divs').html( $sorted_items );
 
	}
</script>


댓글()