티스토리 뷰

javascript 두가지 조건으로 정렬하기

 

조건에 if에 else if를 추가해서 n개의 조건을 줄 수 있습니다.

const studentList = [
  { name: 'kyeongrok', age: 31, math: 85, english: 87 },
  { name: 'jihyun', age: 31, math: 95, english: 97 },
  { name: 'minsup', age: 35, math: 76, english: 84 },
  { name: 'dasom', age: 35, math: 84, english: 73 },
  { name: 'yuna', age: 26, math: 54, english: 67 },
  { name: 'mattheue', age: 29, math: 34, english: 100 },
];

studentList.sort((beforeStudent, nextStudent) => {
  if (beforeStudent.age > nextStudent.age) return 1;
  else if (beforeStudent.age < nextStudent.age) return -1;
  else if (beforeStudent.math > nextStudent.math) return -1;
  else if (beforeStudent.math < nextStudent.math) return 1;
  return 0;
});

console.log(studentList);

 

결과

[ { name: 'yuna', age: 26, math: 54, english: 67 },

  { name: 'mattheue', age: 29, math: 34, english: 100 },

  { name: 'jihyun', age: 31, math: 95, english: 97 },

  { name: 'kyeongrok', age: 31, math: 85, english: 87 },

  { name: 'dasom', age: 35, math: 84, english: 73 },

  { name: 'minsup', age: 35, math: 76, english: 84 } ]

 

위 예제는 두가지 조건으로 정렬하는 예제입니다.

 

첫번째 조건은 나이 오름차순입니다.

 

두번째 조건은 수학점수 내림차순입니다.

 

그래서 결과가 나이가 가장 어린 yuna가 맨 위에 올라가있고 jihyun, kyeongrok은 나이가 31로 같은데 수학점수는 내림차순이므로 수학점수가 더 높은 jihyun이 kyeongrok보다 위에 있습니다.

 

소스코드를 보면 age를 비교하는 11~12번 줄은 return값이 1 -1 순서인데

그 아래 math를 비교 하는 13~14번 줄은 -1, 1 순서입니다.

 

end.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함