I’ll fetch data from an API, When I pass my getServerSideProps data to index.js, the prop array is in order by rank. [1,2,3..etc].
ex: data
JavaScript
x
6
1
[
2
{rank: 1, price: 123},
3
{rank: 2, price: 1958},
4
{rank:3, price: 56}
5
]
6
When I alter that data into a different variable, for example:
JavaScript
1
3
1
const topPrice = data
2
.sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);
3
console log shows data
is now sorted by price too, when I only wanted topPrice
to be sorted, why?
Advertisement
Answer
sort
function alters your original list data
. To avoid that case, you should create a copy of your list before calling sort
JavaScript
1
21
21
1
const data = [{
2
rank: 1,
3
price: 123
4
},
5
{
6
rank: 2,
7
price: 1958
8
},
9
{
10
rank: 3,
11
price: 56
12
}
13
]
14
15
const topPrice = [data]
16
.sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);
17
18
console.log({
19
data,
20
topPrice
21
})
If you want it clearer, you can introduce a new variable to keep the new array
JavaScript
1
22
22
1
const data = [{
2
rank: 1,
3
price: 123
4
},
5
{
6
rank: 2,
7
price: 1958
8
},
9
{
10
rank: 3,
11
price: 56
12
}
13
]
14
15
const copiedData = [data]
16
const topPrice = copiedData
17
.sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);
18
19
console.log({
20
data,
21
topPrice
22
})