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'}
]
*/
随時更新