LoginSignup
0
0

More than 3 years have passed since last update.

オブジェクトの配列で同一のプロパティ値を持つ要素を除外したい

Last updated at Posted at 2020-04-02

やりたいこと


type Item = {
  id: number
  value: string
};

const items: Array<Item> = [
  { id: 1, value: 'foo' },
  { id: 2, value: 'bar' },
  { id: 3, value: 'bar' },
  { id: 4, value: 'baz' },
  { id: 5, value: 'baz' }
];

// 配列itemsからidの値は気にせず、valueの値が同じものを消したい!
const expect: Array<Item> = [
  { id: 1, value: 'foo' }, 
  { id: 2, value: 'bar' },
  { id: 4, value: 'baz' }
];

方法

const result = items.filter((item, index, self) =>
  self.map(e => e.value).indexOf(item.value) === index
);

result.forEach(e => console.log('id:' + e.id + ',' + 'value:' + e.value));
// id:1,value:foo 
// id:2,value:bar 
// id:4,value:baz 
  • filter()やmap()の第3引数ってどういう時に使うんだろう:thinking:と思っていましたが、こういう用途があるんですね。勉強になりました。
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