0

I have a Custom Array like this:

 var myStudentArray1: Array<Student!> = []

     myStudentArray1.append(Student(sCategory: "A+", sName: "Zara"))
     myStudentArray1.append(Student(sCategory: "B-", sName: "Koli"))
     myStudentArray1.append(Student(sCategory: "AA", sName: "Asim"))

I have another String array with same one element of that array1 but in different sequence, like this:

let myStudentArray2: Array<String!> = ["Asim", "Zara", "Koli"]

How do I sort myStudentArray1 based on myStudentArray2 ?

2 Answers 2

1

You will need to iterate through the second array, and for each entry there find corresponding entry in myStudentArray1, and add them to a third array. That will contain items sorted in the order of the second array myStudentArray2

func sortStudents(students: [Student], byNames: [String] ) -> [Student
{

  var result = [Student]()

  for name in byNames {
     let students = students.filter{ $0.sName == name}
     if students.count > 0{
        result.append(students[0])
     }
  }
  return result

}

Now you can call this function to get the sorted results as:

let sortedResults = sortStudents(myStudentArray1, myStudentArray2)
Sign up to request clarification or add additional context in comments.

2 Comments

Getting a consecutive line error here **if let students = students.filter{ $0.sName == name}{ **
@AsimKrishnaDas oh, I had just typed it, now fixed. Pl. check
0

An easy solution is to just sort them both based on the same thing.

myStudentArray1.sortInPlace{$0.sName < $1.sName}
myStudentArray2.sortInPlace{$0 < $1}

for i in 0..<myStudentArray1.count {
    print("\(myStudentArray1[i].sName) = \(myStudentArray2[i])")
}
// Output: Asim = Asim | Koli = Koli | Zara = Zara

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.