0

i have an array and inside of it List type of objects

struct List:Decodable {
    let dt: Int //1593183600
    let dateTime: String //2020-06-26 15:00:00
}

i want to filter the array if object dt is already in array.

examle:

dt: 1593183600,//2020-06-26 21:00:00 dt: 1593216000// 2020-06-27 00:00:00 dt: 1593226800//2020-06-27 03:00:00

the array should not contain 2020-06-27 . it does not matter which one should be remove

my main purplose is writing the weekdays according to time interval values. any diffirent idea would be great

according to your link i tried it like that

let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    //var filteredDays: [List] = []
    let unique = data.unique{formatter.date(from: $0.dateTime)}
    
    print(data.count)//40
    print(unique.count) //1

it should return 5 days but return one

adem
  • 35
  • 5
  • so, you want to get an array of unique `List` objects based on the property `dt`? Here's a similar question: https://stackoverflow.com/questions/33861036/unique-objects-inside-a-array-swift – New Dev Jun 26 '20 at 18:42
  • You should store `Date` instead. Don't use strings for dates, because then you can't do simple date operations like this. This would be trivial with `ate`. – Alexander Jun 26 '20 at 19:02

2 Answers2

1

Use Dictionary(grouping:by) to group the elements by date and then select the first value from each group

let list = Dictionary(grouping: array,
                      by: { Calendar.current.startOfDay(for: Date(timeIntervalSince1970: TimeInterval($0.dt))) })
    .compactMap { $0.value.first }
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-2

You can remove all objects containing the specified date by filtering a list like this:

struct Decodable {
    let dt: Int //1593183600
    let dateTime: String //2020-06-26 15:00:00
}

var list: [Decodable] = []

list.append(Decodable(
    dt: 1,
    dateTime: "2020-06-26 15:00:00"))

list.append(Decodable(
    dt: 1,
    dateTime: "2020-06-27 15:00:00"))


let filteredList = list.filter { !$0.dateTime.contains("2020-06-27") }
print(filteredList)
leiropi
  • 404
  • 1
  • 4
  • 17