用数组作为 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' } ]
广告