LoginSignup
4
2

More than 5 years have passed since last update.

ES6 重複する値を持つ2次元配列をユニークな1次元配列にする書き方

Last updated at Posted at 2017-02-25

前提:ES6

こんなふうに重複するユーザオブジェクトを持つ2次元配列

let groups = [
    {users:[
      {userId:1},
      {userId:2},
    ]},
    {users:[
      {userId:2},
      {userId:3},
    ]},
];

reduceで2次元配列から1次元配列に変換

let array1 = groups.reduce((a, b) => [...a.users,...b.users]);
console.log(array1);
// [
//   {userId:1},
//   {userId:2},
//   {userId:2},
//   {userId:3},
// ]

Objectの配列から整数の配列に変換

let array2 = array1.map( (user) => user.userId );
console.log(array2);
// [1, 2, 2, 3]

Setを使って重複する値を取り除く

let unique = [...new Set(array2)]; 
console.log(unique);
// [1, 2, 3]

メソッドチェーンでつなげて1行で書くと、ぱっと見、何をやってるのかわからん

let unique = [...new Set(groups.reduce((a, b) => [...a.users,...b.users]).map( (user) => user.userId ))]; 
console.log(unique);
// [1, 2, 3]

素朴な書き方

こうした方がわかりやすいという説もある

let userIdList = [];
groups.forEach((group) => {
  group.users.forEach((user) => {
    userIdList.push(user.userId);
  });
});
let unique = Array.from(new Set(userIdList));
console.log(unique);
// [1, 2, 3]

参考

unique values in an array
Array.prototype.reduce()

4
2
1

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
2