Computer >> Máy Tính >  >> Lập trình >> Javascript

Sử dụng mảng làm thứ tự sắp xếp trong 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"}
];

Chúng tôi được yêu cầu viết một hàm JavaScript nhận trong hai mảng như vậy và sắp xếp mảng đối tượng thứ hai trên cơ sở mảng đầu tiên để thuộc tính nội dung của các đối tượng được khớp với các chuỗi của mảng đầu tiên.

Do đó, đối với các mảng ở trên, kết quả đầu ra sẽ giống như -

const output = [
   {"id":3,"content":"this"},
   {"id":1,"content":"is"},
   {"id":2,"content":"my"},
   {"id":4,"content":"custom"},
   {"id":5,"content":"order"}
];

Ví dụ

Mã cho điều này sẽ là -

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));

Đầu ra

Và đầu ra trong bảng điều khiển sẽ là -

[
   { id: 3, content: 'this' },
   { id: 1, content: 'is' },
   { id: 2, content: 'my' },
   { id: 4, content: 'custom' },
   { id: 5, content: 'order' }
]