2

I have two arrays that look something like the below example. What I would like to do is merge the two together. If their keys are equal remove the duplicate and add both of their values together.

Any help is greatly appreciated, many thanks!!

Current Code:

struct Example: Codable {
    var key: String
    var value: Int
}

var first: [Example] = []
var second: [Example] = []

first.append(Example(key: "1", value: 10))
first.append(Example(key: "2", value: 10))
first.append(Example(key: "3", value: 10))

second.append(Example(key: "2", value: 10))
second.append(Example(key: "3", value: 10))
second.append(Example(key: "4", value: 10))


let merged = Array(Dictionary([first, second].joined().map { ($0.key, $0)}, uniquingKeysWith: { $1 }).values)

Currently Prints

Example(key: "3", value: 10)
Example(key: "1", value: 10)
Example(key: "2", value: 10)
Example(key: "4", value: 10)

What I would like do to:

Example(key: "3", value: 20)
Example(key: "1", value: 10)
Example(key: "2", value: 20)
Example(key: "4", value: 10)

1 Answer 1

2

You are nearly there!

In the uniqueKeysWith parameter, you should create a new Example that contains the same key, and the sum of the two parameters' values:

let merged = Array(Dictionary([first, second].joined().map { ($0.key, $0)}, uniquingKeysWith: { Example(key: $0.key, value: $0.value + $1.value) }).values)
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Thank you so much!! 😃

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.