Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้อาร์เรย์เป็นลำดับการจัดเรียงใน 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"}
];

เราต้องเขียนฟังก์ชันที่รับสองอาร์เรย์ดังกล่าวและจัดเรียงอาร์เรย์ที่สองของอ็อบเจ็กต์ตามลำดับของอาร์เรย์แรก โดยจับคู่คุณสมบัติ 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' }
]