Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
Group objects in array based on sequence

I have an array of objects that are a log of actions taken by users. This is an example of what the array looks like:

   [
    {
        "timestamp": "2022-07-14T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-13T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-12T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-11T14:53:32.925Z",
        "action": "Action 2",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-10T14:53:32.925Z",
        "action": "Action 2",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-09T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-08T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-07T14:53:32.925Z",
        "action": "Action 3",
        "user": "User B"
    }
]

The result I am trying to achieve is that the array should be:

[
    {
        "timestamp": "2022-07-14T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-11T14:53:32.925Z",
        "action": "Action 2",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-09T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-07T14:53:32.925Z",
        "action": "Action 3",
        "user": "User B"
    }
]

The array is in order of time.

I don't want to group all duplicates, for example all "action 1" by "User A", only if they occurred one after the other, save the most recent

Any suggestions would be greatly appreciated, TIA!

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

We can use Array.reduce() to add each item to our output array (acc) if it meets any of the criteria:

  • Action has changed.
  • User has changed.
  • Timestamp is greater than the last item.

This should give the required result.

const input = [ { "timestamp": "2022-07-14T14:53:32.925Z", "action": "Action 1", "user": "User A" }, { "timestamp": "2022-07-13T14:53:32.925Z", "action": "Action 1", "user": "User A" }, { "timestamp": "2022-07-12T14:53:32.925Z", "action": "Action 1", "user": "User A" }, { "timestamp": "2022-07-11T14:53:32.925Z", "action": "Action 2", "user": "User A" }, { "timestamp": "2022-07-10T14:53:32.925Z", "action": "Action 2", "user": "User A" }, { "timestamp": "2022-07-09T14:53:32.925Z", "action": "Action 1", "user": "User A" }, { "timestamp": "2022-07-08T14:53:32.925Z", "action": "Action 1", "user": "User A" }, { "timestamp": "2022-07-07T14:53:32.925Z", "action": "Action 3", "user": "User B" } ];

const result = (input.reduce((acc, { timestamp, action, user }) => {
    const { action: lastAction, user: lastUser, timestamp: lastTimestamp } = acc[acc.length - 1] || {};
    if (lastAction !== action || lastUser !== user || lastTimestamp < timestamp) {
        acc.push({ timestamp, action, user });
    }
    return acc;
}, []));

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Santiago Trujillo Relatório

0

Assuming the input array is sorted from new to old. You can loop through them, check each action against the last action present in the result. If it has the same action/user combo, don't add it to the result. If it's not the same user/action, add it to the result. Repeat until you've iterated through all actions.

You can check action/user equality in different ways. One way to do this would be to use your own custom equality function.

const isEqual = (a, b) => a.action === b.action && a.user === b.user;
// you can then compare 2 actions using
isEqual(actionA, actionB)

function solution(actions) {
  const last = array => array[array.length - 1];
  const isEqual = (a, b) => a.action === b.action && a.user === b.user;
  
  const output = [];
  for (const inputAction of actions) {
    const outputAction = last(output) || {};

    // skip if the action/user combination is the same
    if (isEqual(inputAction, outputAction)) continue;
    
    output.push(inputAction);
  }
  return output;
}

console.log(solution([
    {
        "timestamp": "2022-07-14T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-13T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-12T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-11T14:53:32.925Z",
        "action": "Action 2",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-10T14:53:32.925Z",
        "action": "Action 2",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-09T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-08T14:53:32.925Z",
        "action": "Action 1",
        "user": "User A"
    },
    {
        "timestamp": "2022-07-07T14:53:32.925Z",
        "action": "Action 3",
        "user": "User B"
    }
]));

about 4 years ago · Santiago Trujillo Relatório

0

You could use javascrip function sort for you array:

const log = [
  { "timestamp": "2022-07-14T14:53:32.925Z", "action": "Action 1", "user": "User A" },
  { "timestamp": "2022-07-13T14:53:32.925Z", "action": "Action 1", "user": "User A" },
  { "timestamp": "2022-07-12T14:53:32.925Z", "action": "Action 1", "user": "User A" },
  { "timestamp": "2022-07-11T14:53:32.925Z", "action": "Action 2", "user": "User A" },
  { "timestamp": "2022-07-10T14:53:32.925Z", "action": "Action 2", "user": "User A" },
  { "timestamp": "2022-07-09T14:53:32.925Z", "action": "Action 1", "user": "User A" },
  { "timestamp": "2022-07-08T14:53:32.925Z", "action": "Action 1", "user": "User A" },
  { "timestamp": "2022-07-07T14:53:32.925Z", "action": "Action 3", "user": "User B" }
]

const uniqArray = (arr) => {
  return arr.filter((elem, pos, self) => {
    return self.findIndex((item) => item.timestamp == elem.timestamp) == pos
  })
}

const uniqueLog = uniqArray(log, (item) => item.timestamp)
const sortedLog = uniqueLog.sort((row) => new Date(row.timestamp).getTime())

console.log({ sortedLog })

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda