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

รวมคุณสมบัติของอ็อบเจกต์ผ่านฟิลด์ที่ไม่ซ้ำกัน แล้วแสดงข้อมูล - JavaScript

สมมติว่าเรามีอ็อบเจกต์ students ที่มีสองคุณสมบัติคือ names และ marks คุณสมบัติ names เป็นอาร์เรย์ของอ็อบเจกต์ที่แต่ละอ็อบเจกต์มี name และ roll ส่วน marks เป็นอาร์เรย์ของอ็อบเจกต์ที่มี mark และ roll เราต้องรวม marks และ names ตาม roll ที่ตรงกัน

อ็อบเจกต์ students ดังนี้

const students = {
  marks: [
    { roll: 123, mark: 89 },
    { roll: 143, mark: 69 },
    { roll: 126, mark: 91 },
    { roll: 112, mark: 80 }
  ],
  names: [
    { name: 'Aashish', roll: 126 },
    { name: 'Sourav', roll: 112 },
    { name: 'Vineet', roll: 143 },
    { name: 'Kartik', roll: 123 }
  ]
}

กำหนดฟังก์ชัน combineProperties ที่รับอ็อบเจกต์ students และรวมคุณสมบัติในที่เดิม (in-place) โดยไม่ใช้พื้นที่เพิ่มเติม

const combineProperties = (students) => {
  const { marks, names } = students;
  marks.forEach(marksObj => {
    const { roll } = marksObj;
    marksObj.name = names.find(namesObj => namesObj.roll === roll).name;
  })
  delete students['names'];
};
combineProperties(students);
console.log(students);

ความซับซ้อนด้านเวลาคือ O(mn) โดย m และ n คือขนาดของอาร์เรย์ names และ marks ตามลำดับ ความซับซ้อนด้านพื้นที่คือ O(1) แต่จะสร้างคุณสมบัติใหม่ให้แต่ละสมาชิกของอาร์เรย์ marks

โค้ดเต็ม

ตัวอย่าง

const students = {
  marks: [
    { roll: 123, mark: 89 },
    { roll: 143, mark: 69 },
    { roll: 126, mark: 91 },
    { roll: 112, mark: 80 }
  ],
  names: [
    { name: 'Aashish', roll: 126 },
    { name: 'Sourav', roll: 112 },
    { name: 'Vineet', roll: 143 },
    { name: 'Kartik', roll: 123 }
  ]
}
const combineProperties = (students) => {
  const { marks, names } = students;
  marks.forEach(marksObj => {
    const { roll } = marksObj;
    marksObj.name = names.find(namesObj => namesObj.roll === roll).name;
  })
  delete students['names'];
};
combineProperties(students);
console.log(students);

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

{
  marks: [
    { roll: 123, mark: 89, name: 'Kartik' },
    { roll: 143, mark: 69, name: 'Vineet' },
    { roll: 126, mark: 91, name: 'Aashish' },
    { roll: 112, mark: 80, name: 'Sourav' }
  ]
}