Search code examples
arraysswiftdictionaryarray-merge

Swift - Merge two arrays whilst removing keys duplicates and adding array values together


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)

Solution

  • 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)