skip to Main Content

I have an array of objects within a useState hook, it looks something like this:

const[list,setList] = useState(null)

function x() {

setList([
{id:1,name:a},
{id:2,name:b},
{id:3,name:c},
]
}

I want to create a function that will delete a certain amount of these objects from the begining of the array. For example if I were to run the function delete(2), it would delete the first two objects in the array. Leaving list equal to only [{id:3,name:c}]

3

Answers


  1. My Answer:

    let arr = [
    {id:1,name:"e"},
    {id:2,name:"wd"},
    {id:3,name:"das"},
    ]
      
    
    
    function deleteItem(index){
      return arr.filter(ele=>ele.id>2);
    }
    console.log(deleteItem(2))
    

    It would be help. you can use array.filter() function easily.

    Login or Signup to reply.
  2. If you only wish to remove elements from the beginning of the array you could use the shift() function. The shift() removes only the first element of an array. Using this function you could build something like this:

    let arr = [
    {id:1,name:"e"},
    {id:2,name:"wd"},
    {id:3,name:"das"},
    ] 
    
    const removeFirstElements = (numberOfElements) => {
        for (let i = 0; i < numberOfElements; i++){
             arr.shift();
        }
        return arr;
    }
    

    You can then take the result of this function and set it in your list.

    const filteredArr = removeFirstElements(2);
    // filteredArr contains [{id:3,name:"das"}]
    setList(filteredArr);
    
    Login or Signup to reply.
  3. To use this function, you can call it with the desired number of items to delete:

    function deleteFromBeginning(count) {
      setList(prevList => prevList.slice(count))
    }
    

    This will remove the first two items from the list.

    deleteFromBeginning(2);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search