EN
JavaScript - does sort method modify original array?
1 answers
0 points
Does sort()
method modify the original array?
I have the following piece of code:
xxxxxxxxxx
1
let array = [{ id: 1 }, { id: 3 }, { id: 2 }];
2
3
array = array.sort(function(a, b) {
4
return a.id > b.id;
5
});
6
7
console.log(JSON.stringify(array));
Should I redefine array or is it possible to just call sort()
like presented below?
xxxxxxxxxx
1
array.sort(function(a, b) {
2
return a.id > b.id;
3
});
Will the sort()
method change the original array?
1 answer
0 points
The filter()
method itself does mutate the original array. You can use slice()
method to create copyt of the original array and then sort it.
Practical example:
xxxxxxxxxx
1
let array = [{ id: 1 }, { id: 3 }, { id: 2 }];
2
3
let arrayCopy = array.slice();
4
5
arrayCopy.sort(function(a, b) {
6
return a.id - b.id;
7
});
8
9
console.log(JSON.stringify(array)); // [{"id":1},{"id":3},{"id":2}]
10
console.log(JSON.stringify(arrayCopy)); // [{"id":1},{"id":2},{"id":3}]
Note:
Notice that you should use
a.id - b.id
instead ofa.id > b.id
to sort an array.
References
0 commentsShow commentsAdd comment