Front/Vue.js

[Vue.js] Array(배열), Object(객체)에서 sort함수 활용 방법 및 예제

코딩일꾼 2022. 9. 22. 12:55
SMALL

Sort() 함수란?

Array 혹은 Object 의 요소를 사용자가 원하는 특정 기준에 따라 오름,내림차순으로 정리하는 함수이다.

 

Array sort()

배열에서 sort는 비교적 간단하게 구현 가능

문자 정렬
let color = ['white', 'red', 'black', 'blue']
color.sort();	//black, blue, red, white

 

 

숫자 정렬
let number = [130, 110, 72, 252]

number.sort()	// 110, 130, 252, 72 ← 단순 sort는 문자 순서대로 정렬


number.sort(function(a,b){
  return a-b	// 72, 110, 130, 252 ← 오름차순 정렬
})


number.sort(function(a,b){
  return b-a	// 252, 130, 110, 72 ← 내림차순 정렬
})

 

 

날짜 정렬
let date = ['2022-08-08', '2022-03-22', '2022-12-11', '2022-01-24']
date.sort()  // 2022-01-24, 2022-03-22, 2022-08-08, 2022-12-11

 

SMALL

 

Object sort()

객체에서 sort는 특정 키(key)를 기준으로 정렬해줘야 한다.

문자 정렬
let people:[
  {name: '철수', age: 14, birthday:'2004-03-22'},
  {name: '영희', age: 8, birthday:'2009-02-17'},
  {name: '민수', age: 11, birthday:'2007-11-03'},
  {name: '수지', age: 5, birthday:'2012-07-11'}
]

people.sort(function(a,b){
  return a.name < b.name ? -1 : a.name > b.name ? 1 : 0
})		
// 민수, 수지, 영희, 철수 ← 오름차순 정렬

people.sort(function(a,b){
  return a.name < b.name ? -1 : a.name > b.name ? 1 : 0
})
// 철수, 영희, 수지, 민수 ← 내림차순 정렬

 

숫자 정렬
let people:[
  {name: '철수', age: 14, birthday:'2004-03-22'},
  {name: '영희', age: 8, birthday:'2009-02-17'},
  {name: '민수', age: 11, birthday:'2007-11-03'},
  {name: '수지', age: 5, birthday:'2012-07-11'}
]

people.sort(function(a,b){
  return a.age - b.age
})		
// 5, 8, 11, 14 ← 오름차순 정렬

people.sort(function(a,b){
  return b.age - a.age
})
// 14, 11, 8, 5 ← 내림차순 정렬

 

날짜 정렬
let people:[
  {name: '철수', age: 14, birthday:'2004-03-22'},
  {name: '영희', age: 8, birthday:'2009-02-17'},
  {name: '민수', age: 11, birthday:'2007-11-03'},
  {name: '수지', age: 5, birthday:'2012-07-11'}
]

people.sort(function(a,b){
  return new Date(a.birthday) - new Date(b.birthday)
})		
// 2004-03-22, 2007-11-03, 2009-02-17, 2012-07-11 ← 오름차순 정렬

people.sort(function(a,b){
  return new Date(b.birthday) - new Date(a.birthday)
})
// 2012-07-11, 2009-02-17, 2007-11-03, 2004-03-22 ← 내림차순 정렬

 

 

LIST