使用数组作为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函数,该函数接受两个这样的数组,并根据第一个数组对第二个对象数组进行排序,以使对象的content属性与第一个数组的字符串匹配。
因此,对于上述数组,输出应类似于-
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' }
]