출처 : https://www.sitepoint.com/sort-an-array-of-objects-in-javascript/
const singers = [
{ name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
{ name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
{ name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
{ name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];
위 array를 "band" 기준으로 sort
function compare(a, b) {
// Use toUpperCase() to ignore character casing
const bandA = a.band.toUpperCase();
const bandB = b.band.toUpperCase();
let comparison = 0;
if (bandA > bandB) {
comparison = 1;
} else if (bandA < bandB) {
comparison = -1;
}
return comparison;
}
singers.sort(compare);
/* returns [
{ name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
{ name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
{ name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
{ name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }
] */
'DEV > javascript, jQuery' 카테고리의 다른 글
[javascript] var, let, const 차이 ( 완벽 이해 ) (0) | 2020.11.20 |
---|---|
javascript 성능향상 코드스타일 (0) | 2020.11.03 |
[javascript] underber to camel, camel to underbar (0) | 2020.10.28 |
[jQuery] $(this).data('') : 원하는 데이터 값 사용 (0) | 2020.05.24 |
[javascript] 자동 다음 탭 이동 (focus 이동) (0) | 2020.05.24 |