我有以下一系列交易:

const transactions = [
  {
    service: 'Some Text Assignment #1',
    phase: 'Assignment'
  },
  {
    service: 'Some Text Processing #1',
    phase: 'Processing'
  },
  {
    service: 'Some Text Processing #2',
    phase: 'Processing'
  },
  {
    service: 'Some Text Issue Constancy #1',
    phase: 'Issue Constancy'
  },
  {
    service: 'Some Text Quality Control #1',
    phase: 'Quality Control'
  },
  {
    service: 'Some Text Signature and stamp #1',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Signature and stamp #2',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Signature and stamp #3',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Processing #3',
    phase: 'Processing'
  },
  {
    service: 'Some Text Processing #4',
    phase: 'Processing'
  },
  {
    service: 'Some Text Signature and stamp #4',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Signature and stamp #5',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Approved #1',
    phase: 'Approved'
  }
];


我需要获取按phase分组的值,但要满足一定条件:

需要在相同相位值内连续的相位中的最后一个值。

我想要得到的是这样的:

[
  {
    service: 'Some Text Assignment #1',
    phase: 'Assignment'
  },
  {
    service: 'Some Text Processing #2',
    phase: 'Processing'
  },
  {
    service: 'Some Text Issue Constancy #1',
    phase: 'Issue Constancy'
  },
  {
    service: 'Some Text Quality Control #1',
    phase: 'Quality Control'
  },
  {
    service: 'Some Text Signature and stamp #3',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Processing #4',
    phase: 'Processing'
  },
  {
    service: 'Some Text Signature and stamp #5',
    phase: 'Signature and stamp'
  },
  {
    service: 'Some Text Approved #1',
    phase: 'Approved'
  }
]


我试过的是:

transactions.reduce((acc, value) => {
  acc[value.phase] = value;
  return acc;
}, {});


但是我得到的是每个phase的最后一个值。我曾考虑过使用MapsSets。有什么想法吗?

最佳答案

换句话说:您只想过滤出重复的阶段:

  const result =  [...transactions]
    .reverse()
    .filter((el, i, arr) => !i || el.phase !== arr[i - 1].phase)
    .reverse();

07-24 16:12