typescript 将对象Array中的属性与多个数组进行比较,并将匹配元素和不匹配元素返回到两个不同的新数组

bq9c1y66  于 2023-03-13  发布在  TypeScript
关注(0)|答案(1)|浏览(164)

把这个当作我的对象数组-学生

[
  {
    studentName: 'Vishesh Kumar',
    dateOfBirth: '14-03-2023',
    parentName: 'Lalu Kumar',
    examName: 'UPSC CDS',
    dateOfExam: '14-03-1998',
    centerName: 'St Annas High School',
    centerCode: 'RN1001',
    studentEmail: 'Visheshkumar@Gmail.in',
    studentPhoneNumber: 999043139,
    address: 'D-31,Sectory-73,Noida Up India',
    city: 'Noida',
    state: 'UTTAR PRADESH',
    zipcode: 201301
  },
  {
    studentEnrollmentID: 'EN1000006',
    studentName: 'Arnav Singh',
    dateOfBirth: '14-03-2023',
    parentName: 'Arun Singh',
    examName: 'UPSC CDS',
    dateOfExam: '14-03-1998',
    centerName: 'St Annas High School',
    centerCode: 'RN1001',
    studentEmail: 'ArnavSingh@Gmail.in',
    studentPhoneNumber: 6990433540,
    address: 'D-31,Sectory-44,Noida Up India',
    city: 'Noida',
    state: 'UTTAR PRADESH',
    zipcode: 201301
  },
  {
    studentEnrollmentID: 'EN1000004',
    studentName: 'Sanjay Singh',
    dateOfBirth: '14-03-2023',
    parentName: 'Mohan Singh',
    examName: 'UPSC CDS',
    dateOfExam: '14-03-1998',
    centerName: 'St Peters High School',
    centerCode: 'RN1003',
    studentEmail: 'SanjaySingh@Gmail.in',
    StudentPhoneNumber: 9990433538,
    address: 'D-31,Sectory-53,Noida Up India',
    city: 'Noida',
    state: 'UTTAR PRADESH',
    zipcode: 201301
  }
]

现在将centerNames[]和centerCodes[]数组的元素与上述学生的学生对象中的属性进行比较

const centerNames = ['St Annas High School', 'KV Music School']
const centerCodes = ['RN1001','RN1002']

代码应返回两个数组,第一个数组包含与两个数组元素都匹配的学生对象,第二个数组包含与一个或两个数组都不匹配的学生对象
我现有的代码看起来像if和else在for循环中运行的循环,如果数组大小增加,这就不理想了

for (student of students) {
      if (student.examCode == examCode) {
        const newStudent = await new Student(student);
        await newStudent.save().then(async (result: any) => {
          studentsUploaded.push(result);
        }).catch(async (error: any) => {
          studentsRejected.push(newStudent);
          errors.push(error);
        });
      } else {
        studentsRejected.push(student);
        errors.push(`${examCode} does not match`);
      }
    }
qco9c6ql

qco9c6ql1#

尝试:

const students = [{/*...*/}] // array of students
const centerNames = ['St Annas High School', 'KV Music School']
const centerCodes = ['RN1001','RN1002']
const matched = students.filter(s => centerNames.includes(s.centerName) && centerCodes.includes(s.centerCode))
const unmatched = students.filter(s => !(centerNames.includes(s.centerName) && centerCodes.includes(s.centerCode)))

关于复杂性:
时间复杂度为O(2(n * k * h)),其中n是students数组的长度,k和h是centerNames和centerCodes的长度。考虑k和h常数,总复杂度为O(n),这是遍历所有students数组所需的最小复杂度

相关问题