Получить последнее значение непрерывного повторного свойства в объекте - PullRequest
0 голосов
/ 21 мая 2019

У меня есть этот массив транзакций :

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. Я подумал об использовании Maps или Sets. Некоторые идеи?

Ответы [ 6 ]

2 голосов
/ 21 мая 2019

Вы можете добавить элемент к выводу, если следующий элемент в массиве не имеет phase с текущим элементом

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"}];

const output = []

transactions.forEach((o, i) => {
  const next = transactions[i + 1] || {};
  if (next.phase !== o.phase)
    output.push(o)
})

console.log(output)
1 голос
/ 21 мая 2019

Другими словами: вы просто хотите отфильтровать повторяющиеся фазы:

  const result =  [...transactions]
    .reverse()
    .filter((el, i, arr) => !i || el.phase !== arr[i - 1].phase)
    .reverse();
1 голос
/ 21 мая 2019

Использовать Array.reduce следующим образом

  • Ведение переменной, в которой хранится последняя посещенная фаза
  • Для каждого элемента проверить, совпадает ли фаза с сохраненным значениемв переменной фазы
  • Если значение отличается или не определено (для первого значения), нажмите значение в массиве и задайте значение фазы в переменной фаза
  • , иначе обновите последнее значение в результирующем массивес предметом

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"}];

let phase;
const result = transactions.reduce((a,c) => {
  if(phase && c.phase == phase) a[a.length-1] = c;
  else { a.push(c); phase = c.phase;}
  return a;
}, []);
console.log(result);
1 голос
/ 21 мая 2019

Сгруппируйте соседние предметы с Array.reduce(), затем сопоставьте и возьмите последний элемент в каждой группе:

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"}]

const result =
  transactions.reduce((r, o, i, arr) => {
    if(!i || o.phase !== arr[i - 1].phase) r.push([]);
    
    r[r.length - 1].push(o);
  
    return r;
  }, [])
  .map(arr => arr[arr.length - 1]);
  
console.log(result);
0 голосов
/ 21 мая 2019

Вы можете проверить соседние значения и добавить, как только увидите несоответствующие фазы

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"}]


let final = transactions.reduce((op,inp,index)=>{
  if( index + 1 ===  transactions.length){
    if(transactions[index-1].phase !== inp.phase){
      op.push(inp)
    }
  }
  else if(transactions[index+1].phase !== inp.phase){
    op.push(inp)
  }
  return op
},[])

console.log(final)
0 голосов
/ 21 мая 2019

Вы пытались решить проблему почти правильно, но вы должны проверить последний вставленный объект, а не любой вставленный объект.

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'
  }
];

let out = transactions.reduce((acc, value) => {
  let last = acc.length && acc[acc.length - 1];
  if (last && last.phase === value.phase)
    last.service = value.service;
  else
    acc.push(value);
  return acc;
}, []);

console.log(out);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...