Sanjeev Gautam
Sanjeev Gautam

Reputation: 39

How to use map function to get alternative indexes data from an array in swift

struct Product {
    let name: String
    let weight: Double
}

let productsList = [Product(name: "AAA", weight: 1),
                    Product(name: "BBB", weight: 2),
                    Product(name: "CCC", weight: 3),
                    Product(name: "DD", weight: 4),
                    Product(name: "RR", weight: 5),
                    Product(name: "EEE", weight: 6),
                    Product(name: "FGT", weight: 7),
                    Product(name: "DSF", weight: 8),
                    Product(name: "VCVX", weight: 9),
                    Product(name: "GFDHT", weight: 10)]

print(productsList.map { $0.name })

I am getting all the product names from the above line but I want to get only names from odd indexes using map. Is it possible?

Upvotes: 3

Views: 2746

Answers (2)

Martin R
Martin R

Reputation: 539965

You can map the odd indices to the corresponding product name:

let oddIndexedProducts = stride(from: 1, through: productsList.count, by: 2)
    .map { productsList[$0].name }

print(oddIndexedProducts) // ["BBB", "DD", "EEE", "DSF", "GFDHT"]

Another way is to use compactMap on the enumerated() sequence:

let oddIndexedProducts = productsList.enumerated().compactMap {
    $0.offset % 2 == 1 ? $0.element.name : nil
}

As a rule of thumb: “filter + map = compactMap” (“flatMap” in Swift 3).

Upvotes: 2

Sweeper
Sweeper

Reputation: 273178

Here's one way of doing this:

print(
    productsList
        .enumerated()
        .filter { $0.offset % 2 == 1 }
        .map { $0.element.name }
)

The enumerated method turns each product into a 2-tuple that contains both the product and its index in the array (offset). You then filter to leave only the products that have an odd (or even) index. After that, you need to map the 2-tuples to the name of the product.

Upvotes: 5

Related Questions