按 JavaScript 中陣列的索引來排序
假設我們有以下物件陣列 -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];我們需要編寫一個 JavaScript 函式,該函式採用一個這樣的陣列。
該函式應按物件的 index 屬性對該陣列按升序排序。
然後,該函式應將排序後的陣列對映到一個字串陣列,其中每個字串都是物件 name 屬性值對應的值。
因此,對於上述陣列,最終輸出應如下所示 -
const output = ["a", "b", "c", "d"];
示例
相應的程式碼為 -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];
const sortAndMap = (arr = []) => {
const copy = arr.slice();
const sorter = (a, b) => {
return a['index'] - b['index'];
};
copy.sort(sorter);
const res = copy.map(({name, index}) => {
return name;
});
return res;
};
console.log(sortAndMap(arr));輸出
控制檯中的輸出為 -
[ 'a', 'b', 'c', 'd' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP