자바 스크립트에서 정렬를 하기 위해서는 sort() 함수를 이용한다.


1. 숫자 정렬


예를 들어 


var a = [33,4, 111, 22]

a.sort()

결과 : [111, 22, 33, 4]



위와 같이 기본적으로는 알파벳으로 정렬한다.


숫자로 정렬하고자 하면 아래와 같이 sort 함수의 function을 인자로 넘겨준다.


a.sort(function(a,b){

      return a-b;

});

결과 : [4, 22, 33, 111]


이유는 첫번째 인자가 두번째 인자보다 앞에 나타나야 한다면 0보다 작은 숫자

아니면 0보다 큰 숫자를 리턴하면 된다고 한다.


두 값이 동등하다면(순서가 무의미 하다면) 0 을 리턴해야 한다.



그럼 역순으로 정렬하고자 하면

a.sort(function(a,b){

      return b-a;

});


이다. 



2. 문자 정렬


만약 대소문자 구분 안하고 정렬하고 싶다면 모든 문자를 임시로 소문자나, 대문자를 만들어서 작업하면 된다.

그냥 정렬일 경우


var a = ['ant', 'Bug', 'cat', 'Dog']

a.sort()

결과 : ["Bug", "Dog", "ant", "cat"]



대소문자 구분안함.


a.sort(function(s, t){

var a = s.toLowerCase();

var b = t.toLowerCase();

if(a<b) return -1;

if(a>b) return 1;

return 0;

});


결과 : ["ant", "Bug", "cat", "Dog"]


위와 같이 적용할 수 있다.




'WEB > javascript' 카테고리의 다른 글

자바 스크립트 상속 구조  (0) 2014.07.05
json 변환  (0) 2014.06.05

// original classes

function Animal(name, numLegs) {

    this.name = name;

    this.numLegs = numLegs;

    this.isAlive = true;

}

function Penguin(name) {

    this.name = name;

    this.numLegs = 2;

}

function Emperor(name) {

    this.name = name;

    this.saying = "Waddle waddle";

}


// set up the prototype chain

Penguin.prototype = new Animal();

Emperor.prototype = new Penguin();


var myEmperor = new Emperor("Jules");


console.log( myEmperor.saying ); // should print "Waddle waddle"

console.log( myEmperor.numLegs ); // should print 2

console.log( myEmperor.isAlive ); // should print true

'WEB > javascript' 카테고리의 다른 글

[javascript] 정렬하기  (0) 2014.08.01
json 변환  (0) 2014.06.05

array를 json으로 변경


JSON.stringify(Array);

'WEB > javascript' 카테고리의 다른 글

[javascript] 정렬하기  (0) 2014.08.01
자바 스크립트 상속 구조  (0) 2014.07.05

+ Recent posts