0
0

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 3 years have passed since last update.

配列に入ったvalueが重複しているオブジェクトを取り除きたい

Last updated at Posted at 2021-03-04

目的

user_idがかぶってるやつを取り除きたい。
(あとからDBに追加されたレコードを優先したりさせなかったりしたい。)

【前提となる配列】

const items = [
  { id: 1, user_id: 1, num: 1 },
  { id: 2, user_id: 2, num: 2 },
  { id: 3, user_id: 1, num: 11 },
  { id: 4, user_id: 2, num: 12 },
  { id: 5, user_id: 3, num: 13 },
];

①idが大きいものを優先(上書き)しながら重複を取り除く

Mapを使う方法

const updateItems = [...new Map(items.map((value) => [value.user_id, value])).values()];

console.log(updateItems);
// [ { id: 3, user_id: 1, num: 11 },
//   { id: 4, user_id: 2, num: 12 },
//   { id: 5, user_id: 3, num: 13 } ]

sortとfilterを組み合わせる方法

const updateItems = items
  .sort((a, b) => {
    return b.id - a.id;
  })
  .filter((item, index, array) => {
    return array.findIndex((item2) => item.user_id === item2.user_id) === index;
  });

console.log(updateItems);
// [ { id: 5, user_id: 3, num: 13 },
//   { id: 4, user_id: 2, num: 12 },
//   { id: 3, user_id: 1, num: 11 } ]

②idが小さいものを優先しながら重複を取り除く

const updateItems = items
    .sort((a, b) => b.user_id - a.user_id)
    .filter((value, index, array) => {
      return array.findIndex((value2) => value.user_id === value2.user_id) === index;
    });

console.log(updateItems);
// [ { id: 5, user_id: 3, num: 13 },
//   { id: 2, user_id: 2, num: 2 },
//   { id: 1, user_id: 1, num: 1 } ]

他にもこんな方法があるよ!があったら是非教えていただきたいです!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?