Home > Software design >  How to move array object to first index
How to move array object to first index

Time:10-31

How to bring array object to first Index

   struct ScheduleDateTime {
     var startDate: String?
     var endDate: String?
     var isScheduled: Bool?
    }

var scheduleDateTime = [ScheduleDateTime]()
    func reArrange(){
        if let scheduleList = scheduleDateTime{
          if  scheduleList.count > 1 {
              for each in scheduleList {
                  if each.isScheduled == true {
                    // Bring the item to first Index.

                  }
              }
            } 
        }
    }

How to bring the array Index to first position based on above isSchedule == true condition

CodePudding user response:

You can do a sort based on comparing isScheduled. This will move all isScheduled == true items to the front of the array.

let input : [ScheduleDateTime] = 
  [.init(startDate: "Item1", endDate: nil, isScheduled: false),
   .init(startDate: "Item2", endDate: nil, isScheduled: false),
   .init(startDate: "Item3", endDate: nil, isScheduled: true),
   .init(startDate: "Item4", endDate: nil, isScheduled: false),
   .init(startDate: "Item5", endDate: nil, isScheduled: true)]

let output = input.sorted(by: { $0.isScheduled == true && $1.isScheduled != true })

print(output.map(\.startDate!))

Yields:

["Item3", "Item5", "Item1", "Item2", "Item4"]

  • Related