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