kiran
kiran

Reputation: 4409

How to move array object to first index

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

Upvotes: 0

Views: 834

Answers (1)

jnpdx
jnpdx

Reputation: 52347

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"]

Upvotes: 1

Related Questions