在 JavaScript 中使用数组作为排序顺序

javascriptweb developmentfront end technologyobject oriented programming

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' }
]

相关文章


有用资源