Reputation: 69
is there anyway we can merge/union the two sub arrays inside a json array
jsonArray = [["abc","hello","hai"]["true","false","hai"]]
expected output would be ["abc","hello","hai","true","false"]
any help would be highly appreciated!
Thanks
Upvotes: 0
Views: 247
Reputation: 943
You could first flatten it and then turn it into a Set to remove duplicates. For example:
val jsonArray = listOf(listOf("abc","hello","hai"), listOf("true","false","hai")) // This is the same as [["abc","hello","hai"]["true","false","hai"]]
val flattenedSetOfJsonArray = map.flatten().toSet()
println(flattenedSetOfJsonArray) // prints [abc, hello, hai, true, false]
If you want to flatten deeply nested lists you can use this helper method (credits to)
fun List<*>.deepFlatten(): List<*> = this.flatMap { (it as? List<*>)?.deepFlatten() ?: listOf(it) }
Now use this method like this:
val jsonArray = listOf(listOf("abc","hello","hai"), listOf("true","false","hai"), listOf(listOf("true", "false", "abc")))
val flattenedSetOfJsonArray = jsonArray.deepFlatten().toSet()
println(flattenedSetOfJsonArray) // prints [abc, hello, hai, true, false]
Upvotes: 1