MyDocs

# 配列をユニークにする

JavaScript

set を使う

配列を Set に変換。

const arr = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9, 9, 9]
const set = new Set(arr)

console.log(set)
// Set(10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }

Set を配列に変換。

const arr = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9, 9, 9]
const set = new Set(arr)

const setToAArr = Array.from(set)

console.log(setToAArr)
// [
//   0, 1, 2, 3, 4,
//   5, 6, 7, 8, 9
// ]

スプレッド構文を使う。

const arr = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9, 9, 9]
const set = new Set(arr)

const setToAArr = [...set]

console.log(setToAArr)
// [
//   0, 1, 2, 3, 4,
//   5, 6, 7, 8, 9
// ]

map を使う

配列を Map に変換。

const arr = [{id: 1}, {id: 2}, {id: 2}, {id: 3}]

const m = new Map(arr.map(e => [e.id, e]))

console.log(m)
// Map(3) { 1 => { id: 1 }, 2 => { id: 2 }, 3 => { id: 3 } }

Golang

package main

import (
	"fmt"
)

func main() {
	arr := []int{0, 0, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 9, 9, 9}
	m := make(map[int]struct{})
	uniqArr := make([]int, 0)

	for _, v := range arr {
		if _, ok := m[v]; !ok {
			m[v] = struct{}{}
			uniqArr = append(uniqArr, v)
		}
	}
	
	fmt.Println(uniqArr) // [0 1 2 3 4 5 6 7 8 9]
}