LoginSignup
1
0

More than 1 year has passed since last update.

Goで辞書型配列の値の長さでソートする

Posted at

やりたいこと

map[string]stringな配列で、値の長さでソートしたい。

この記事によるとGolangのmapは明確な順序を持たないので、値の長さでソートしたキーを配列として取得することにする。

どうやったか

mapのままソートする方法がわからなかったので、一度構造体に落とし込んだ後にsortする。

非常に冗長で汚いので、もっとわかりやすく明確でスマートな方法があったら教えてほしいです。

コード

package main

import (
	"sort"
	"fmt"
)

var FoodList = map[string]string{
	"Menu1": "Orange",
	"Menu2": "Banana",
	"Menu3": "Apple",
	"SpecialMenu": "YakisobaCake",
}

func SortWithValueLen(baseMap map[string]string)([]string){
	var rtn []string
	
	type temp struct{
		index string
		value string
	}

	var tempList []temp
	for index, value := range baseMap{
		tempList = append(tempList, temp{index: index, value: value})
	}

	sort.Slice(tempList, func(i, j int) bool {
		return len(tempList[i].value) > len(tempList[j].value)
	})

	for _, temp := range tempList{
		rtn = append(rtn, temp.index)
	}
	return rtn
}

func main(){
	fmt.Println(SortWithValueLen(FoodList))
}

結果

値の長い順にKeyがソートされる

[SpecialMenu Menu1 Menu2 Menu3]

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0