Search code examples
arrayskotlinmergecollectionsmutablelist

How to merge two arrays by ID in Kotlin?


I have two arrays like:

val array1 = arrayOf(
  arrayOf("001", "Product name", "Product group"),
  arrayOf("002", "Product name", "Product group"),
  arrayOf("003", "Product name", "Product group"),
  arrayOf("004", "Product name", "Product group"),
  arrayOf("005", "Product name", "Product group")
)

val array2 = arrayOf(
  arrayOf("001", "Property1"),
  arrayOf("002", "Property2"),
  arrayOf("004", "Property4")
)

How can I merge both arrays in one by use of the ID (first column)? The result table (array or mutablelist) should contain ALL columns from array1 and only match results from array2 from second column. It should look like following structure:

val array3 = arrayOf(
  arrayOf("001", "Product name", "Product group", "Property1"),
  arrayOf("002", "Product name", "Product group", "Property2"),
  arrayOf("003", "Product name", "Product group", "NO MATCH"),
  arrayOf("004", "Product name", "Product group", "Property4"),
  arrayOf("005", "Product name", "Product group", "NO MATCH")
)

Solution

  • First, we need to create a lookup map for the second list, so we can easily search for the property by its ID. Then we can use it when transforming the first list:

    val prop2ById = array2.associate { it[0] to it[1] }
    val array3 = array1.map { it + arrayOf(prop2ById.getOrDefault(it[0], "NO MATCH")) }
    

    I assume the ID in the second array is unique.

    Also, it seems you represent objects as arrays. If each column is meaningful, it means a very specific piece of data, we should not represent this as an array, but as an object or optionally a map. Using arrays here is much more error-prone and bad for the code quality in general.