0

## Golang map判斷重複 並刪除

[map[userId:1] map[userId:2] map[userId:3] map[userId:3]]

### 2 個回答

0
listennn08
iT邦高手 7 級 ‧ 2020-05-25 13:17:56

package main

import (
"fmt"
"reflect"
)

func unique(arr []map[string]int) []map[string]int {
for index, _:= range arr {
for i := index +1; i < len(arr) ; i++ {
if (reflect.DeepEqual(arr[i], arr[index]) ) {
arr = append(arr[:i], arr[i+1:]...);
i-=1 // 因為刪除資料 arr 長度會縮減， 如果有兩個以上重複會比對不到
}
}
}
return arr;
}

func main() {
var map1, map2, map3 map[string]int;
map1, map2, map3 = make(map[string]int), make(map[string]int), make(map[string]int);
map1["userId"] = 1;
map2["userId"] = 2;
map3["userId"] = 3;

array := []map[string]int{map1, map2, map3, map3};
fmt.Println(unique(array)); //[map[userId:1] map[userId:2] map[userId:3]]
}

demo on Go Playground

0
z9905080
iT邦見習生 ‧ 2020-05-26 21:44:54

func unique(arr []map[string]int) []map[string]int {
for index, _:= range arr {
for i := index +1; i < len(arr) ; i++ {
if reflect.DeepEqual(arr[i], arr[index]) {
arr = append(arr[:i], arr[i+1:]...)
}
}
}
return arr;
}

func main() {
map1, map2, map3,map4 := make(map[string]int), make(map[string]int), make(map[string]int), make(map[string]int)
map1["userId"] = 1
map2["userId"] = 2
map3["userId"] = 3
map4["userId"] = 3
map4["key"] = 3

array := []map[string]int{map1, map2, map3, map4}
fmt.Println(unique(array)) //[map[userId:1] map[userId:2] map[userId:3]]
}

outPut: [map[userId:1] map[userId:2] map[userId:3] map[key:3 userId:3]]

func unique(arr []map[string]int) []map[string]int {
for index, _:= range arr {
for i := index+1; i< len(arr); i++ {
if (arr[index]["userId"] == arr[i]["userId"]) {
arr = append(arr[:i], arr[i+1:]...);
i-=1
}
}
}
return arr;
}

demo