1

I am looking for better approach to sort an array of objects on the basis of array elements inside the object.

I have an array of objects to be shown as rows in UITableView

The row objects is having array of columns. There is a button to sort, which sort the rows on the basis of selected column

enter image description here

My object is bit complex but here putting forward simple object.

Example:

class AnimalOnEarth{
var animals:[Animals] = []
}
class Animals{
var animalName:String = ""
} 

var listOfAnimal:[AnimalOnEarth] = [obj1,obj2,obj3,obj4]

I wanted to sort listOfAnimal on the basis of animalName reside as an element of array in animals object.

Kindly suggest

Soniya
  • 600
  • 7
  • 34

1 Answers1

1

You could use an array's sort(by: ) method.

listOfAnimal.sort { animalOnEarth1, animalOnEarth2 in
    // Code... (condition for sort)
    
    // Example: If we want to sort by length of `animals` list.
    return animalOnEarth1.animals.count < animalOnEarth2.animals.count

    // This will compare each `AnimalOnEarth` object in the array 
    // (animalOnEarth1) to the one after it (animalOnEarth2).
    // If this block returns true, it will sort the first 
    // (I.e. `animalOnEarth1`) before the next (`animalOnEarth2`). 
    // If it returns `false`, it will do the opposite.
}

enter image description here

In response to comment:

Thanks for your response, in your solution you are comparing array count though I need to compare values inside the child array to sort parent array - Soniya

It's the same concept. Let's take your image for example, and say we wanted to sort by application fee, lowest to highest.

rowObjectsArray.sort { rowObject1Array, rowObject2Array in
    
    // Get rowObject1Array's application fee. Something like...
    var row1ApplicationFee: Int = rowObject1Array.first(where: { $0 is ApplicationFeeObjectName }).applicationFee

    // Get rowObject2Array's application fee. Something like...
    var row2ApplicationFee: Int = rowObject2Array.first(where: { $0 is ApplicationFeeObjectName }).applicationFee

    // Finally, compare...
    if row1ApplicationFee < row2ApplicationFee {
        return true // meaning we want row1 to stay before row 2
    }
    else {
        return false // meaning we want row1 to actually be after row 2.
    }
}
Eric
  • 569
  • 4
  • 21
  • Thanks for your response, in your solution you are comparing array count though I need to compare values inside the child array to sort parent array – Soniya Apr 25 '22 at 05:54
  • @Soniya see my revised answer. – Eric Apr 26 '22 at 19:37