gpt4 book ai didi

javascript - .map 内的排序会影响原始数组而不是返回新数组

转载 作者:行者123 更新时间:2023-11-28 17:04:09 26 4
gpt4 key购买 nike

我有一个二维数字数组:array1。我想映射 array1 中的每个数组并对每个数组中的数字进行排序并将它们返回到一个新数组:sortedRows。我知道映射数组会返回一个新数组,但是当我在映射过程中对每个内部数组进行排序时,它会对 array1 中的所有数字以及排序行进行排序。

我已经尝试过将 array1 单独映射到行,然后映射/排序到排序行,并且我尝试使用扩展运算符进行复制 (rows = [...array1])。下面这两种尝试都得到相同的结果。

let array1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2], 
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]

let sortedRows = array1.map(arr => arr.sort((a, b) => a - b))

console.log(array1)
console.log(sortedRows)
// expected

[ [5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]
[ [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ]


//actual

[ [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ]
[ [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ]


最佳答案

.sort 改变原始数组,所以当你有

array1.map(arr =>

那里的arr引用现有的子数组 - 如果您对其调用.sort,您将更改该子数组。

首先复制数组:

const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b))

let array1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2], 
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]];

const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b));

document.write(array1.join('<br>'));
document.write('<br><br><br>' + sortedRows.join('<br>'));

关于javascript - .map 内的排序会影响原始数组而不是返回新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com