0

I have two arrays of the same size and I sort the second one. How can I array the first one to match?

Basic example (imagine replacing Ints with Strings):

var array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1] 

array2.sort = ({ $0 > $1})

Result:

array2 is now [8, 6, 5, 5, 5, 5, 4, 4, 3, 2, 1]

How to sort array1's index value to match array2?

array1 should now be [6, 5, 0, 4, 7, 9, 3, 8, 2, 1, 0]
1
  • 3
    I would say make one array of object and sort object... Commented Feb 10, 2015 at 7:23

1 Answer 1

4

Zip2, sorted and map

array1 = map(sorted(Zip2(array1, array2), {$0.1 > $1.1}), { $0.0 })

Combining filter

var array1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1]

func isEven(x:Int) -> Bool {
    return x % 2 == 0
}

let result = map(sorted(filter(Zip2(array1, array2), { isEven($0.1) }), {$0.1 > $1.1}), { $0.0 })
// -> ["6", "5", "3", "8", "1"]

As you can see, the line is too complex, you might want to Array method chain syntax:

let result2 = Array(Zip2(array1, array2))
    .filter({ isEven($0.1) })
    .sorted({ $0.1 > $1.1 })
    .map({ $0.0 })

Anyway, if your array2 is [PFObject], you can implement the function something like:

func isOpen(restaurant: PFObject, forTime time: String, onDay day: Int) -> Bool {

    // return `true` if the restaurant is open, `false` otherwise

}
Sign up to request clarification or add additional context in comments.

5 Comments

Does this work for functions too? If I call a function for array2 filterAreOpen(detailsForFoodPhotos, forTime: time.time, onDay: time.dayOfWeek) and map array1 the same way?
Would it look something like this: map(filterAreOpen(detailsForFoodPhotos, forTime: time.time, onDay: time.dayOfWeek), { $0.0 })
what is filterAreOpen, maybe this? If so, I don't think it will work. I will add the basic example combining filter.
Thank you so much. But will the filter work if my filterAreOpen function returns an array? Or will I need to create a new function that can filter individual data? (please see edited question)
The latter: you need to create a new function. It's not so hard, your filterAreOpen already have filter logic. You can extract that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.