How to get only the last values for every unique name in a struct array in Swift4?

swift array custom objects unique
swift array get object at index
swift dictionary
swift array index
swift map
swift array filter
swift array of objects
get unique values from array swift

It has the following struct.

    struct LastValue {
        var name: String
        var price: Int
    }

    var lastValue = [
        LastValue(name: "coffee", price: 100),
        LastValue(name: "coffee", price: 200),
        LastValue(name: "coffee", price: 150),
        LastValue(name: "coffee", price: 200),
        LastValue(name: "dessert", price: 500),
        LastValue(name: "dessert", price: 700),
        LastValue(name: "dessert", price: 600),
        LastValue(name: "dessert", price: 800)    
    ]

I want only the last values ​​of each name. In other words, In other words, I want to bring only the last values ​​of coffee and desert.

lastValue is dynamic and another value can be added.

The result I want is:

LastValue(name: "coffee", price: 200),
LastValue(name: "dessert", price: 800)
struct LastValue {
    let name: String
    let price: Int
}

var array = [
    LastValue(name: "coffee", price: 100),
    LastValue(name: "coffee", price: 200),
    LastValue(name: "coffee", price: 150),
    LastValue(name: "coffee", price: 200),
    LastValue(name: "dessert", price: 500),
    LastValue(name: "dessert", price: 700),
    LastValue(name: "dessert", price: 600),
    LastValue(name: "dessert", price: 800)
]

Solution 1
let lastValues = array.reduce([]) { (result, value) -> [LastValue] in
    var updatedResult = result
    updatedResult.removeAll(where: {$0.name == value.name})
    updatedResult.append(value)
    return updatedResult
}

for value in lastValues {
    print(value.name, value.price)
}
Solution 2

@Evgeniy's approach also seems nice although it can improved like this.

let names: Set<String> = Set(array.map( {$0.name} ))

var lastValues: [LastValue] = []
for name in names {
    lastValues.append(lastValue.last(where: {$0.name == name})!)
}

for lastValue in lastValues {
    print(lastValue.name, lastValue.price)
}
print(lastValues)

I think this takes atleast 1 + n passes at the array. (One to find the unique names in the array and n passes to find the last for n names. I do not know how last(where: works but i'm guessing it goes through the array every time?)


Edit: Improved the first approach after @Paulw11's comments.

swift, to get only the last values for every unique name in a struct array in Swift4? struct LastValue { var name: String var price: Int } var lastValue  I want only the last values of each name. In other words, In other words, I want to bring only the last values of coffee and desert. lastValue is dynamic and another value can be added. The result I want is: LastValue(name: "coffee", price: 200), LastValue(name: "dessert", price: 800)

let lastCoffee = lastValue.last(where: { $0.name == "coffee" })
let lastDesert = lastValue.last(where: { $0.name == "dessert" })

Array, Use the first and last properties for safe access to the value of the array's first and Suppose you need to store a list of the names of students that are signed up for a Because any arbitrary subclass of NSArray can become an Array , there are no If you change a reference to an object in one array, only that array has a  In other words, give INDEX the list and a row number, and INDEX will retrieve a value to add to the unique list. The hard work is figuring out the ROW number to give INDEX, so that we get unique values only. This is done with MATCH and COUNTIF, and the main trick is here:

Alternatively with Dictionary(grouping:by:

let lastValue = [
    LastValue(name: "coffee", price: 100),
    LastValue(name: "coffee", price: 200),
    LastValue(name: "coffee", price: 150),
    LastValue(name: "coffee", price: 200),
    LastValue(name: "dessert", price: 500),
    LastValue(name: "dessert", price: 700),
    LastValue(name: "dessert", price: 600),
    LastValue(name: "dessert", price: 800)
]

let result = Dictionary(grouping: lastValue, by: {$0.name}).compactMap{$0.1.last}

// [{name "coffee", price 200}, {name "dessert", price 800}]

Use Swift's reduce function to get unique values from a collection , Use Swift's reduce function to get unique values from a collection Then, the last combined value is returned. This goes on until all the elements of the array are added. It returns a new array with unique values only. type called Visitor, which is a struct holding two variables: name and yearOfVisit. n is the total number of elements in the field name of structure S, that is, n = numel([S(:).(name)]). a is a cell array if any field values in the field name contain a character vector or if the field values are not uniform in type; otherwise a is the same type as the field values.

Swift in 24 Hours, Sams Teach Yourself, Not only can properties, methods, initializers, and subscripts be made public, private, in an array, and writing aDictionary["username"] would return the value for the Swift enables you to create your own subscripts for any class, struct, or enum keyword rather than the func keyword, and subscripts do not have names. For example, you can use unique(A(:,vars)), where vars is a positive integer, a vector of positive integers, a variable name, a cell array of variable names, or a logical vector. Alternatively, you can use vartype to create a subscript that selects variables of a specified type.

Get Started with this Guide to Data Structures in Swift, 1 2 3 4 struct DataPair { var first: Data var second: Data } don't have to specify the supported types in the name of our structure. The values must not be unique: each value can appear multiple Swift implements arrays - and all other collection types - as generic a value can only appear once in a set. In this case, the lookup value is 2, and in our array, we will only get 1’s or errors. So it scans the entire array and returns the position of the last 1 – which is the last matching value of the name. Find the Last Occurrence – Using Custom Function (VBA) Let me also show you another way of doing this.

Stop Using Structs! - Commencis, I hear all the time people say 'prefer value types over reference types'. What if we are all getting it wrong? the value around (between functions or threads) there will be a unique Swift's collection types (Dictionary, Array, String, Set etc.) Basically copy-on-write provides creating another instance only  Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,,NameN,ValueN. Example: A = cellfun(@mean,C,'UniformOutput',false) returns the outputs from mean in a cell array. Use the 'UniformOutput',false name-value pair if C

Comments
  • Your code blocks are mismatched. There is coffee and dessert in the first block, apples and oranges in the second.
  • Oh, I'm sorry. Fixed the code. thanks
  • Is your array static or dynamic?
  • My array is dynamic and I can continue to add the Name column.
  • Is your name proprerty static? Names will be dessert and coffee only or new names may come?
  • If you please elaborate what this reduce function is doing.
  • @iPeter it reduces the current array to the result that you want it to be.
  • Why do you suggest using a class rather than a struct? If anything you should change the var name and var price to lets
  • @Paulw11 If i use a struct, it tells me .first is a get-only property while reducing which is because struct is a value type?
  • Yes, because you are trying to mutate the object. Don't do that.
  • Nice answer! :)