用陣列作為 JavaScript 中的排序順序
const sort = ["this","is","my","custom","order"];
const myObjects = [
{"id":1,"content":"is"},
{"id":2,"content":"my"},
{"id":3,"content":"this"},
{"id":4,"content":"custom"},
{"id":5,"content":"order"}
];我們需要編寫一個 JavaScript 函式,它可以接收兩個這樣的陣列,並根據第一個陣列來對第二個物件陣列進行排序,以便物件的內容屬性與第一個陣列中的字串匹配。
因此,對於上面的陣列,輸出應如下所示:
const output = [
{"id":3,"content":"this"},
{"id":1,"content":"is"},
{"id":2,"content":"my"},
{"id":4,"content":"custom"},
{"id":5,"content":"order"}
];示例
程式碼如下:
const arrLiteral = ["this","is","my","custom","order"];
const arrObj = [
{"id":1,"content":"is"},
{"id":2,"content":"my"},
{"id":3,"content":"this"},
{"id":4,"content":"custom"},
{"id":5,"content":"order"}
];
const sortByReference = (arrLiteral, arrObj) => {
const sorted = arrLiteral.map(el => {
for(let i = 0; i < arrObj.length; ++i){
if(arrObj[i].content === el){
return arrObj[i];
}
};
});
return sorted;
};
console.log(sortByReference(arrLiteral, arrObj));輸出
控制檯中的輸出如下:
[
{ id: 3, content: 'this' },
{ id: 1, content: 'is' },
{ id: 2, content: 'my' },
{ id: 4, content: 'custom' },
{ id: 5, content: 'order' }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP