AskBee
AskBee

Reputation: 17

How can I get the numbers/elements less than 5 of an array on swift code?

My array is this let numbers = [3, 6, 9, 2, 4, 1] How can I get the numbers less than 5 of an array on swift code? I try using this

let numbers = [3, 6, 9, 2, 4, 1]
var minNumber = 5
for number in numbers {
    minNumber = min(minNumber, number as Int)
}
print("The min numbers are\(minNumber)")

But only gives me one number and I need like 1, 2, 3, 4 I don't know if I should sort the array first or if I should just look up the number. I'm sorry if it's a silly question but I'm learning.

I hope someone can help me, I would really appreciate it link of the photo I'm not allowed to upload: https://i.sstatic.net/Odixz.png

Upvotes: 0

Views: 537

Answers (2)

gcharita
gcharita

Reputation: 8327

You can use filter(_:) function of Array like this:

let numbers = [3,6,9,2,4,1]
var minNumber = 5
let lessThan5 = numbers.filter { $0 < minNumber }

Upvotes: 2

Jav Solo
Jav Solo

Reputation: 736

You might want to create another array and store them in there. Here I use the loop and append the values in the array to minNumbers array. There are many other ways to do this, but this is pretty straightforward.

let numbers = [3,6,9,2,4,1]
var minNumbers = [Int]()
var minNumber = 5
for number in numbers {
    if number < minNumber {
        minNumbers.append(number)
    }
}

print("The minimum numbers are: \(minNumbers)")

Upvotes: 0

Related Questions