ES6 array sort 並建立新矩陣

Array 排序

Array.sort( ) 本身是不給予新的記憶體位置的,只是修改矩陣內的數值排列

const people = [
    { name: "Alice", height: 165 },
    { name: "Bob", height: 180 },
    { name: "Charlie", height: 155 }
];


people.sort((a, b) => a.height - b.height);
console.log(people); // new sort to people 但是記憶體位置是一樣的

利用 Array.slice()

const sortedByHeightAscending = 
    people.slice().sort((a, b) => a.height - b.height);

console.log(sortedByHeightAscending); // new sort
console.log(people); // 還是原來那個

利用 ES6 解構式

const sortedByHeightAscending = 
    [...people].sort((a, b) => a.height - b.height);


console.log(sortedByHeightAscending); // new sort
console.log(people); // 還是原來那個

Comments

タイトルとURLをコピーしました