Search code examples
iosarraysswiftarray-map

Exclude element in array when iterating using map


I have code like below

let myNums = getXYZ(nums: [1,2,3,4,5])

func getXYZ(nums: [Int]) -> [Int] {
let newNum = nums.map { (num) -> Int in

    if num == 2 {
    //do something and continue execution with next element in list like break/fallthrough
        return 0
    }
    return num
}

return newNum

}

print(myNums)`

This prints [1,0,3,4,5]

but i want the output to be [1,3,4,5]. How can I exclude 2? I want to alter the if statement used so as to not include in array when it sees number 2

I have to use .map here but to exclude 2..is there any possibility

Please let me know


Solution

  • I'd simply do a filter as described as your problem, you want to filter the numbers by removing another number.

    var myNums = [1, 2, 3, 4, 5]
    let excludeNums = [2]
    
    let newNum = myNums.filter({ !excludeNums.contains($0) })
    
    print(newNum) //1, 3, 4, 5
    

    If you need to do a map, you could do a map first then filter.

    let newNum = myNums.map({ $0*2 }).filter({ !excludeNums.contains($0) })
    print(newNum) //4, 6, 8, 10
    

    This maps to multiplying both by 2 and then filtering by removing the new 2 from the list. If you wanted to remove the initial 2 you would have to filter first then map. Since both return a [Int] you can call the operations in any order, as you deem necessary.