1

Here is the sample code:

var myArray = [["one", "two"], ["three", "four"]]

var filteredArray = myArray.filter{ value in value[1] != "four"}

filteredArray //[["one", "two"]]

This code is supposed to filter out any array that contains "four". It does it properly, but only because I target specific array with value[1] because I know it contains "four". How should I reformat this code so I don't need to specify specific array, so it will scan all values in there? When using a "for loop", we have a declared "i" variable we can use. But how to do similar with .filter function ?

Also, even more specific, how could I reformat this code so I can filter array and exclude all that have "four" but specifically as their second value (index [1]) and not if they have "four" in any other index position as in previous requirement. Again in the absence of an "i" variable, I don't see how to do it. Your help is appreciated.

1 Answer 1

1

Knowing that the filter callback receives an inner array at each iteration, we can use reduce on that array to check if it contains the four string:

var filteredArray = myArray.filter {
    let count = $0.reduce(0) {
        $0 + ($1 == "four" ? 1 : 0)
    }

    return count == 0
}

In the reduce closure, if one or more elements is four, the return value will be an integer greater than zero.

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

1 Comment

smart it helped me get it tsk

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.