4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【javascript】配列の重複を削除する

Posted at

ES6で記載します。

普通の配列の場合

Setに入れることで重複が消えるので、それを配列に戻す。

var dupArray = [1,1,4,5,1,4,1,9,1,9,8,1,0];
var arr = Array.from(new Set(dupArray));
// -> [1, 4, 5, 9, 8, 0]

Object配列の場合

一意に保持したいkeyを指定し、それを利用してフィルタリングする。

var dupObjectsArray = [
    { userId: 1, class: "2-B", name: "Rinko Shirokane" },
    { userId: 2, class: "3-B", name: "Ako Udagawa" },
    { userId: 3, class: "2-B", name: "Yukina Minato" },
    { userId: 4, class: "2-A", name: "Risa Imai" },
    { userId: 5, class: "2-B", name: "Sayo Hikawa" },
];
var key = "class"; // このケースではclassの重複を消す

var keymap = new Set(dupObjectsArray.map(e => e[key]));
var objectsArray = dupObjectsArray.filter(e => {
	return keymap.has(e[key]) && keymap.delete(e[key]);
});

// objectsArray ->
// 0: {userId: 1, class: "2-B", name: "Rinko Shirokane"}
// 1: {userId: 2, class: "3-B", name: "Ako Udagawa"}
// 2: {userId: 4, class: "2-A", name: "Risa Imai"}

この方法だと最初に一致した要素が残る。
後方一致にしたい場合は、配列をreverseで入れ替える。

// (共通部分略)
var objectsArray = dupObjectsArray.reverse().filter(e => {
	return keymap.has(e[key]) && keymap.delete(e[key]);
});

// objectsArray ->
// 0: {userId: 5, class: "2-B", name: "Sayo Hikawa"}
// 1: {userId: 4, class: "2-A", name: "Risa Imai"}
// 2: {userId: 2, class: "3-B", name: "Ako Udagawa"}
4
1
3

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?