user14822019
user14822019

Reputation: 25

Get particular index from array

I'm having an array: var myArray = ["","dfg","erte","","asd"]

How can I get the index of those elements which doesn't have ""..?

I have this code:

for i in myArray {
                                                                    
  let index = myArray.firstIndex(where: {$0 == i})

} 

This gives me the index of all elements. But I want the index of those elements which doesn't have ""

Upvotes: 0

Views: 99

Answers (4)

Duncan C
Duncan C

Reputation: 131398

If your goal is to create an array of the indexes of all non-empty elements in your string array, you can do that using enumerated() and compactMap:

var myArray = ["","dfg","erte","","asd"]

let indexes = myArray.enumerated().compactMap { (index, value) in
    value.isEmpty ? nil : index
}

print(indexes)

That outputs:

[1, 2, 4]

If, instead, you want the index of the first non-empty element, you could use code like this:

if let firstNonEmptyIndex = myArray.firstIndex(where: {!$0.isEmpty}) {
    print("The entry at index \(firstNonEmptyIndex) is empty")
} else {
    print("No entries in the array are empty.")
}

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51831

Here is an option is using filter

let range = myArray.indices.filter { !myArray[$0].isEmpty }

To access the array using range you can then do

for index in range {
    print(myArray[index])
}

Of course if the end goal is to get an array of all non-empty values then you can filter on the array directly

let notEmpty = myArray.filter { !$0.isEmpty }

Upvotes: 1

Raja Kishan
Raja Kishan

Reputation: 18904

You can use compactMap it remove nil value too(if array has)

var myArrayIndex = myArray.enumerated().compactMap { (index, data) -> Int? in
    if !data.isEmpty {
        return index
    }
    return nil
}
print(myArrayIndex)

Sort way:

var myArrayIndex = myArray.enumerated().compactMap{!$0.element.isEmpty ? $0.offset : nil}
print(myArrayIndex)

Upvotes: 0

mehmett
mehmett

Reputation: 111

You can get index with offset value in here:

var str = ["","123","345","","789"]

for i in str.enumerated(){
    if i.element != "" {
        print(i.offset)
    }
}

Upvotes: 0

Related Questions