Home > Net >  How to iterate through this array applying a decimal increase
How to iterate through this array applying a decimal increase

Time:03-11

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.

CodePudding user response:

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

CodePudding user response:

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)

  • Related