0
0

More than 3 years have passed since last update.

JavaScript 配列の中の重複を省く簡単な方法

Posted at

配列の重複を省く簡単な方法

プリミティブ値

  • 数字
  • 文字列
  • 真偽値
//重複を省きたい配列
const old_array = [1,1,1,2,2,2,3,4];
const new_array = [...new Set(old_array)]

console.log(new_array);
// [1, 2, 3, 4]

Set
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Set

Object

やりかた

  1. ソートします。
  2. 隣接するObjectと比較して重複しているなら省く。

以上

実践

const old_array = [{k:3},{k:1},{k:2},{k:3},{k:1},{k:2},{k:3},{k:3}];

//ソート
old_array.sort((o1,o2)=> o1.k - o2.k);

//何を重複とするか決める。
//今回だとkの値が一緒だと重複と見なします。
function compare(o1,o2){
  return o1.k === o2.k
}

//あとは、隣と比較して同じだったら省くだけ!
const new_array = old_array.filter(function(element,index,array){
  if(index === 0) return true;
  return !compare(element,array[index-1])
})
console.log(new_array)
// [{"k":1},{"k":2},{"k":3}]

0
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
0
0