There are two arrays – first one is about dates, and the second one shows spendings, being made that day:
var arrayOfDates = [01.07, 01.07, 03.07, 04.07, 05.07, 05.07, 05.07]
var arrayofCosts = [3, 8, 2, 2, 8, 6, 9]
I want to filter the arrayOfDates
for unique elements. And in the second array show the highest-value spending for each day.
So the result should be:
var arrayOfDatesModifed = [01.07, 3.07, 04.07, 05.07]
var arrayofNumbersModifed = [8, 2, 2, 9]
So this idea consists of 3 phases:
- Filter
arrayOfDates
for unique elements - For each unique date find corresponding item(s) in
arrayofCosts
- Find the biggest value in
arrayofCosts
for each date
Though each of this tasks individually may be simple, I cant figure it out how to accomplish them altogether. Your help will be very much appreciated
2
Answers
I agree with those with comments. Working with individual arrays is going to be a real pain.
Let’s implement a struct to hold our data.
These are just the entries from your example:
The first thing I would do is group all entries by date:
Which gives us an unordered Dictionary where the key is the date and the value is an array of entries having the same date:
The next thing I would do is extract the entry with the max cost in each group and discard the entries with the lower costs. We don’t need those. So now we have an array of entries where the low cost elements have been filtered out.
This gives us:
As you can see, the array is not sorted by the date. So we can do that now
And finally that gives us:
The above simple for loop also be the solution but its not optimised one.
The swift language have many advanced concept in the latest versions, We should avoid the above complex way to solve the problem.
It just an example for: Should not solve the problem for current situation , should consider the future perspective as well.
Its not the solution for you Sergey_VC , just trying to help someone trying quick fix in Online.