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 ta cần viết hàm JavaScript nhận vào hai mảng như vậy và sắp xếp mảng đối tượng thứ hai dựa trên mảng thứ nhất sao cho thuộc tính content của các đối tượng khớp với chuỗi của mảng thứ nhất.
Kết quả mong đợi:
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ã thực hiện:
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));Kết quả
Kết quả in ra console:
[
{ id: 3, content: 'this' },
{ id: 1, content: 'is' },
{ id: 2, content: 'my' },
{ id: 4, content: 'custom' },
{ id: 5, content: 'order' }
]