skip to Main Content
    const arr=[]

    let id=0
    app.post('/book',(req,res)=>{
      payload={body: req.body,id: id+1}
      id=id+1
      arr.push(payload)
      console.log("arr",arr);
      return res.send("success")
    })

`this is how I created the push function in an array with default id

i try to delete element from this array by its id using pop or using some loop`

2

Answers


  1. first of all you need to convert the id into number then use filter to delete the required element like so:

    const deleteId = parseInt(req.body.id);
    
    arr = arr.filter(item => item.id !== deleteId);
    
    console.log("arr", arr);
    
    Login or Signup to reply.
  2. This is a tested snippet which works successfully:

        const arr=[]
    
        let id=0
        while (id < 10) {
          payload={body: "some text " + id,id: id+1}
          id=id+1
          arr.push(payload)
        }
        
        let toRemove = arr.map((item, index) => ((item.id == 3) ? index : false)).filter(item => (item !== false));
        
        if (toRemove.length) {
            for (let indexToRemove = toRemove[0]; indexToRemove < arr.length - 1; indexToRemove++) {
                arr[indexToRemove] = arr[indexToRemove + 1];
            }
            
            arr.pop();
        }
        
        console.log(arr);

    I’m:

    • mapping the items of an array to their index if the id matches and false otherwise (assuming that an id is unique)
    • then filter the result by the items not being false, getting the index to remove
    • then check whether the id was found
    • and if so, loop the array starting from that index to the end
    • and copy the next item into the current one
    • except for the last element which is popped

    Tested with an id of 3, you can use the value you want instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search