如何在不改变原始数组的情况下对数组进行排序? [英] How can you sort an array without mutating the original array?
问题描述
假设我想要一个排序函数,它返回输入数组的排序副本.我天真地尝试了这个
Let's suppose I wanted a sort function that returns a sorted copy of the inputted array. I naively tried this
function sort(arr) {
return arr.sort();
}
我用这个测试了它,这表明我的 sort
方法正在改变数组.
and I tested it with this, which shows that my sort
method is mutating the array.
var a = [2,3,7,5,3,7,1,3,4];
sort(a);
alert(a); //alerts "1,2,3,3,3,4,5,7,7"
我也试过这种方法
function sort(arr) {
return Array.prototype.sort(arr);
}
但它根本不起作用.
有没有一种直接的方法可以解决这个问题,最好是一种不需要手动滚动我自己的排序算法或将数组的每个元素复制到一个新元素的方法?
Is there a straightforward way around this, prefereably a way that doesn't require hand-rolling my own sorting algorithm or copying every element of the array into a new one?
推荐答案
排序前需要先复制数组.使用 es6 制作浅拷贝的一种方法:
You need to copy the array before you sort it. One way to make a shallow copy with es6:
const sorted = [...arr].sort();
作为数组字面量的展开语法(从 mdn 复制):
The spread-syntax as array literal (copied from mdn):
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
这篇关于如何在不改变原始数组的情况下对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!