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

88
Visualizações
Want to remove objects that are before specific value

const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  },
]

Above array can have multiple objects with id: 'R' and i want to ignore all objects that are before id: 'R'.

Expected:

const array = [
{ id: "U", 
T: "005"}]

Can someone please help with this

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

  • Using Array#map, get the list of ids
  • Using Array#lastIndexOf, get the index of the last occurrence of the id "R"
  • Using Array#splice, get the target sub-array following this index

const array = [ { id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" } ];

const ids = array.map(({ id }) => id);
const index = ids.lastIndexOf("R") + 1;
const res = array.splice(index);

console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

Agree with all the above answers, but why do we go with the map, slice, reverese and all. We can simply use just a loop instead of those as below. Considering time as well, if the array length increases the combination of any of the map, reverse, slice, splice takes much time

const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  },
];

let newArr = [];

for(let i = array.length - 1; i >= 0; i--){
if(array[i].id === 'R') break;
else newArr.push(array[i])
}
console.log(newArr);

about 4 years ago · Juan Pablo Isaza Relatório

0

Reverse array, Find the index of first R, slice array...

const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  }
]

const cheak = (element) => element.id === "R"


console.log(array.reverse().slice(0, array.findIndex(cheak)).reverse());

about 4 years ago · Juan Pablo Isaza 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