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

Reduxのreducer内でよく使うJavascriptの描き方まとめ

Last updated at Posted at 2016-02-20

keyとvaluを持つ配列に対して、
keyの重複がないように元の配列を新しい配列で更新し、keyで降順にソートする


state = [
  {key: 1, val: 'aaa'},
  {key: 2, val: 'bbb'},
  {key: 3, val: 'ccc'},
  {key: 4, val: 'ddd'}
];

payload = [
  {key:2, val: 'BBB'},
  {key:3, val: 'CCC'},
  {key:5, val: 'EEE'}
];

const newState = state.filter(o => 
    payload.map(n => n.key).indexOf(o.key) === -1
).concat(payload).sort((a, b) =>
    a.key > b.key ? 1 : -1
);

/*
結果はこちら
[
    {key: 1, val: 'aaa'},
    {key: 2, val: 'BBB'},
    {key: 3, val: 'CCC'},
    {key: 4, val: 'ddd'},
    {key: 5, val: 'EEE'}
]
*/

随時更新

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