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

112
Visualizações
How to iterate through this array applying a decimal increase

I have a list which has an Id column. When a user adds an item it starts with 3.1, and continues 3.2, 3.3, 3.4 as each item is added.

The problem: If a user deletes for e.g. 3.3 in a list of up to 3.7, the order of these Id's won't be sequential. I'm attempting with the below to iterate through the Id's to reorder them, starting with 3.1 for top row of the list.

Here's the delete function:

 const deleteItem = () => {
        const currentArray = myArr;
        for (var i = 0; i < currentArray .length; i++) {
  
            if (currentArray [i] == selectedItem) {
                currentArray .splice(i, 1);
            }
            setMyArr([...currentArray ]);
        }
          for(var i = 3.1; i < currentArray .length; i++){
        i + 0.1;
            
          }
    };

The first for, deletes the item and sets the array of items, the second for is my attempt to reset the order of the Ids.

I have looked at several solution on SO but not found them useful.

How would I do this.

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

0

You could filter the item you want to delete, and then set again the ids like this:

currentArray
  .filter(item => item !== selectedItem) // Remove the selectedItem from the array
  .map((item, idx) =>({...item, id:3.1 + index * 0.1}) // Reset the ids sequentially
about 4 years ago · Juan Pablo Isaza Relatório

0

The array indexes and length will not work with decimal values.

What I think you want to do is to iterate the array and set the id based on the id of the first one:

const finalArray = currentArray.map((item,index)=> ({...item, id:3.1 + index * 0.1});

as noted in comments to the question index * 0.1 is subject to rounding errors, so you should apply your roundings.

(I'm assuming your items are objects and have an id attribute)

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