이미 API로 전달받은 데이터가 있다는 가정하에 해보겠다!
list.sort(function (f, s) {
const idF = f.id;
const idS = s.id;
if (idF > idS) {
return -1;
}
if (idF < idS) {
return 1;
}
return 0;
});
const compare = (key) => (f, s) => {
return f[key] > s[key] ? -1 : f[key] < s[key] ? 1 : 0;
};
list.sort(compare('id'));
list.sort(function(f,s) {
const idF = f.id;
const idS = s.id;
if (idF < idS) {
return -1;
}
if(idF > idS) {
return 1;
}
return 0;
});
위의 함수를 삼항연산자로 바꾸면
list.sort((f,s) => f.id < s.id ? -1 : f.id > s.id ? 1 : 0);
이것도 마찬가지로 확인해보면 오름차순으로 변경됨을 확인할 수 있다.
list.sort((f,s) => f.id - s.id)