Post

[Vue] 데이터 정렬과 데이터 보존 sort() [...array]

[Vue] 데이터 정렬과 데이터 보존 sort() [...array]

sort()

sort() 함수는 문자를 알파벳순으로 정렬해준다.
숫자를 정렬하고 싶으면 아래와 같이 써준다.

sort() 함수는 원본 데이터를 변형한다. 원본데이터를 보존하고 싶으면 map, filter 함수를 써준다.

1
2
3
[1,5,8,6].sort(function(a,b){
	return a-b;
});

정렬 예제

1
<button type="button" @click="priceSort">가격순 정렬</button>
1
2
3
4
5
6
7
methods: {
  priceSort(){
    this.원룸들.sort(function(a,b){
      return a.price - b.price;
    });
  }
},

array 데이터 보존

array는 특성상 다른 변수에 대입했어도 서로 값을 공유하기 때문에 [...array] 처럼 복사본을 만들어 프로그램이 해야한다.

1
2
3
4
5
6
7
8
9
10
11
data(){
  return {
    원룸들오리지널: [...data],
    원룸들: data,
  }
},
methods: {
  sortBack(){
    this.원룸들 = [...this.원룸들오리지널];
  },
},

전체, 내림차순, 오름차순, 가나다순 정렬

1
2
3
4
<button type="button" @click="sortBack">전체</button>
<button type="button" @click="priceSortDesc">가격 내림차순 정렬</button>
<button type="button" @click="priceSortAsc">가격 오름차순 정렬</button>
<button type="button" @click="ProductSort">가나다순 정렬</button>
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
32
33
34
export default {
  name: 'App',
  data(){
    return {
      원룸들오리지널: [...data],
      원룸들: data
    }
  },
  methods: {
    sortBack(){
      this.원룸들 = [...this.원룸들오리지널];
    },
    priceSortDesc(){
      this.원룸들.sort(function(a,b){
        return a.price - b.price;
      });
    },
    priceSortAsc(){
      this.원룸들.sort(function(a,b){
        return b.price - a.price;
      });
    },
    ProductSort(){
      this.원룸들.sort(function(a, b){
        if(a.title.toLowerCase() > b.title.toLowerCase())
          return 1;
        else if(a.title.toLowerCase() < b.title.toLowerCase())
          return -1;
        else
          return 0;
      });
    }
  },
}
This post is licensed under CC BY 4.0 by the author.