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

121
Visualizações
adding item in to react state at certain position related to the item at hand?

How to update state array to add a value after related position rather than at the end of the array ? in the example below for example I want rice to go after rice rather than after bananas ? , this current logic is making thing really mixed when I want to render items according to what the user has selected to be the first item.

let stateArr = [{item : cucumber}, {item : rice }, {item: bannan }, {item : rice }]

// current state logic 

[...stateArr, newItem ]

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

0

If you want to keep things immutable, you can slice your array at the point you want to insert the new item, and spread those two slices around your new value.

let stateArr = [
    { item: "cucumber" },
    { item: "rice" },
    { item: "bannan" },
    { item: "fish" },
];

// First, find the location of the item you want to insert _after_
const riceIndex = stateArr.findIndex(({ item }) => item === "rice");

const newItem = { item: "crab" };

// Next, slice _right after_ that item (+ 1)
const newState = [
    ...stateArr.slice(0, riceIndex + 1),
    newItem,
    ...stateArr.slice(riceIndex + 1),
];

console.log(newState);

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