[javascript] sort

[javascript] sort updated_at: 2024-03-25 15:51

javascript sort 에 관한 다양한 예제

object를 소팅하는 예제들입니다.

예제 1

var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000, helicopter:400, rocket:8*60*60}
var sortable = [];
for (var vehicle in maxSpeed)
  sortable.push([vehicle, maxSpeed[vehicle]])
sortable.sort(function(a, b) {return a[1] - b[1]})
// 결과 : [["bike", 60], ["motorbike", 200], ["car", 300],["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

See the Pen javascript- sort by younghyeong ryu (@wangta69) on CodePen.

예제 2

function sortObject(obj) {
  var arr = [];
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      arr.push({
      'key': prop,
      'value': obj[prop]
      });
    }
  }
  arr.sort(function(a, b) { return a.value - b.value; });
  //arr.sort(function(a, b) { a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); //use this to sort as strings
  return arr; // returns array
}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var arr = sortObject(list);
// 결과 : [{key:"bar", value:15}, {key:"me", value:75}, {key:"you", value:100}, {key:"foo", value:116}]

예제 3

var objs = [ 
  { first_name: 'Pig',    last_name: 'Bodine'   },
  { first_name: 'Lazslo', last_name: 'Jamf'     },
  { first_name: 'Pirate', last_name: 'Prentice' }
];

function compare(a,b) {
  if (a.first_name < b.first_name)
    return -1;
  if (a.first_name > b.first_name)
    return 1;
  return 0;
}

objs.sort(compare);
// 결과 : [{first_name: 'Lazslo', last_name: 'Jamf'}, {first_name: 'Pig', last_name: 'Bodine'}, {first_name: 'Pirate', last_name: 'Prentice'}]

예제 4

var maxSpeed	= new Array();
maxSpeed[1] = {type:"car", speed:300}
maxSpeed[2] = {type:"bike", speed:60}
maxSpeed[5] = {type:"motorbike", speed:200}
maxSpeed[8] = {type:"airplane", speed:1000}
maxSpeed[10] = {type:"helicopter", speed:400}
maxSpeed[12] = {type:"rocket", speed:8*60*60}

function compare(a,b) {
  if (a.type < b.type)
    return -1;
  if (a.type > b.type)
    return 1;
  return 0;
}
maxSpeed.sort(compare);
// 결과 : [{type:"airplane", speed:1000}, {type:"bike", speed:60}, {type:"car", speed:300}, {type:"helicopter", speed:400}, {type:"motorbike", speed:200}, {type:"rocket", speed:8*60*60}]
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글