Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(go) combine two array and keep order
package main
import "log"
func main() {
result := combineAndKeepOrder([]string{"a", "b", "c"}, []string{"c", "a", "d"})
log.Println(result, testEq(result, []string{"c", "b", "a", "d"}))
result = combineAndKeepOrder([]string{}, []string{"c", "a", "d"})
log.Println(result, testEq(result, []string{"c", "a", "d"}))
result = combineAndKeepOrder([]string{"a", "b", "c"}, []string{"d", "a", "c"})
log.Println(result, testEq(result, []string{"d", "b", "a", "c"}))
result = combineAndKeepOrder([]string{"a", "b", "c"}, []string{})
log.Println(result, testEq(result, []string{"a", "b", "c"}))
}
func combineAndKeepOrder(origins []string, new []string) []string {
position := 0
for idxO, k := range origins {
for _, v := range new {
if v == k {
origins[idxO] = new[position]
position++
break
}
}
}
if position < len(new) {
origins = append(origins, new[position:]...)
}
return origins
}
func testEq(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment