숫자와 문자열을 포함한 배열의 정렬할 경우
localeCompare()이라는 함수를 사용한다
// 오름차순
const getSingleValueAsc = (arr) => {
return arr.sort(function (a, b) {
return a.localeCompare(b, undefined, {
numeric: true,
sensitivity: 'base',
});
});
};
// 내림차순
const getSingleValueDesc = (arr) => {
return arr.sort(function (a, b) {
return b.localeCompare(a, undefined, {
numeric: true,
sensitivity: 'base',
});
});
};
console.log(getSingleValueAsc(strNum));
// [ 'a1', 'a2', 'a10', 'a12', 'j1', 'j2', 'j5', 'j10', 'j13', 'j19' ]
console.log(getSingleValueDesc(strNum));
// [ 'j19', 'j13', 'j10', 'j5', 'j2', 'j1', 'a12', 'a10', 'a2', 'a1' ]
숫자와 문자열을 포함한 객체를 포함한 배열의 정렬할 경우
const valueOfKeyArr = [
{ name: 'a10', foo: 'foo', bar: 'bar' },
{ name: 'a2', foo: 'foo', bar: 'bar' },
{ name: 'a1', foo: 'foo', bar: 'bar' },
{ name: 'a12', foo: 'foo', bar: 'bar' },
{ name: 'joker5', foo: 'foo', bar: 'bar' },
{ name: 'joker10', foo: 'foo', bar: 'bar' },
{ name: 'joker2', foo: 'foo', bar: 'bar' },
{ name: 'joker1', foo: 'foo', bar: 'bar' },
{ name: 'joker13', foo: 'foo', bar: 'bar' },
{ name: 'joker9', foo: 'foo', bar: 'bar' },
];
// 오름차순
const getValueOfKeyAsc = (arr, key) => {
return arr.sort(function (a, b) {
const valueOfKeyA = a[key].toUpperCase();
const valueOfKeyB = b[key].toUpperCase();
return valueOfKeyA.localeCompare(valueOfKeyB, undefined, {
numeric: true,
sensitivity: 'base',
});
});
};
//내림차순
const getValueOfKeyDesc = (arr, key) => {
return arr.sort(function (a, b) {
const valueOfKeyA = a[key].toUpperCase();
const valueOfKeyB = b[key].toUpperCase();
return valueOfKeyB.localeCompare(valueOfKeyA, undefined, {
numeric: true,
sensitivity: 'base',
});
});
};
getValueOfKeyAsc(valueOfKeyArr, 'name');
/*
[
{ name: 'a1', foo: 'foo', bar: 'bar' },
{ name: 'a2', foo: 'foo', bar: 'bar' },
{ name: 'a10', foo: 'foo', bar: 'bar' },
{ name: 'a12', foo: 'foo', bar: 'bar' },
{ name: 'joker1', foo: 'foo', bar: 'bar' },
{ name: 'joker2', foo: 'foo', bar: 'bar' },
{ name: 'joker5', foo: 'foo', bar: 'bar' },
{ name: 'joker9', foo: 'foo', bar: 'bar' },
{ name: 'joker10', foo: 'foo', bar: 'bar' },
{ name: 'joker13', foo: 'foo', bar: 'bar' }
]
*/
getValueOfKeyDesc(valueOfKeyArr, 'name');
/*
[
{ name: 'joker13', foo: 'foo', bar: 'bar' },
{ name: 'joker10', foo: 'foo', bar: 'bar' },
{ name: 'joker9', foo: 'foo', bar: 'bar' },
{ name: 'joker5', foo: 'foo', bar: 'bar' },
{ name: 'joker2', foo: 'foo', bar: 'bar' },
{ name: 'joker1', foo: 'foo', bar: 'bar' },
{ name: 'a12', foo: 'foo', bar: 'bar' },
{ name: 'a10', foo: 'foo', bar: 'bar' },
{ name: 'a2', foo: 'foo', bar: 'bar' },
{ name: 'a1', foo: 'foo', bar: 'bar' }
]
*/
참조포스트
https://velog.io/@kingth/javascript-stringnumber-%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%A0%95%EB%A0%AC
localeCompare
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
Nov 26, 2022
Views 116