프론트엔드 센트럴파크 (☞゚ヮ゚)☞

고차함수 - sort()(문자) 본문

Javascript

고차함수 - sort()(문자)

자라나라나무나무나 2022. 5. 26. 13:36

배열에 대문자와 소문자가 섞여 있는 경우, toUpperCase() 함수를 이용해 대문자로 다 바꾼 후 

콜백함수를 사용하여 문자 크기를 비교한다.

 

오름차순

let ascending_order = function(x,y) {
    x = x.toUpperCase();
    y = y.toUpperCase();

    if (x > y) return 1;
    else if (y > x) return -1;
    else return 0;
};

let fruits = ["apple", "Orange", "orange", "melon"];

console.log(fruits.sort(ascending_order));


내림차순

let descending_order = function(x,y) {
    x = x.toUpperCase();
    y = y.toUpperCase();

    if (x < y) return 1; // 변환
    else if (y < x) return -1;
    else return 0;
}

let fruits = ["apple", "Orange", "orange", "melon"];

console.log(fruits.sort(descending_order));

 


let ascending_order = function(x, y) {
    if(typeof x === "string") x = x.toUpperCase();
    if(typeof y === "string") y = y.toUpperCase();

    return x > y ? 1 : -1;
};

let descending_order = function(x, y) {
    if(typeof x === "string") x = x.toUpperCase();
    if(typeof y === "string") y = y.toUpperCase();

    return x < y ? 1: -1; 
};

let nums = [ 1, -1, 4, 10, 20, 12]; // case 1
let fruits = ["apple", "Orange", "orange", "melon"]; // case 2

console.log(nums.sort(ascending_order));
console.log(nums.sort(ascending_order));

console.log(fruits.sort(ascending_order));
console.log(fruits.sort(descending_order));


문자열을 코드로 변환하여 비교하는 경우

const numbers = ['마', '가', '라', '나', '다'];

const orderNumbers = numbers.sort(function(a, b) {
    return b.localeCompare(a);
});

console.log(orderNumbers);

arrow function(화살표 함수)

const numbers = ['마', '가', '라', '나', '다'];

const 내림차순 = (a,b) => b.localeCompare(a);
const orderNumbers = numbers.sort(내림차순);

console.log(orderNumbers);

 

'Javascript' 카테고리의 다른 글

고차함수 - forEach()  (0) 2022.05.26
고차함수 - sort()(숫자)  (0) 2022.05.26
배열값을 문자열로 변환 - join  (0) 2022.05.24
배열 변형 - sort, reverse  (0) 2022.05.24
배열탐색 - indexOf, lastIndexOf, includes  (0) 2022.05.24
Comments