0

Best way to remove a row off an object based off a certain condition?

Down below I made a function to remove any row where the difference of the amount within latest row and any other row is greater than 300.

bank_data = [{"arrival_time":"12:00","amount":"900","id":"BS"},  
{"arrival_time" :"12:00","amount":"300","id":"BD"},
{"arrival_time" :"01:00","amount":"400","id":"SW"},
{"arrival_time" :"03:00","amount":"800","id":"OS"},
{"arrival_time" :"03:00","amount":"500","id":"SF"},
{"arrival_time" :"04:00","amount":"600","id":"SJ"},
{"arrival_time" :"04:00","amount":"600","id":"FS"},
{"arrival_time" :"06:00","amount":"900","id":"JC"}];

function update_list(obj){
    if(obj.length > 0) {
        latest = obj.length -1; 
        for(var i = 0; i < obj.length; i++){
            if((obj[latest].amount - obj[i].amount) > 300){
                obj.splice(i, 1);//remove the ith row of the object
            }
        }
    }
    return obj;
}


Goal Result

bank_data = [{"arrival_time":"12:00","amount":"900","id":"BA"},  
{"arrival_time" :"03:00","amount":"800","id":"OS"},
{"arrival_time" :"04:00","amount":"600","id":"SJ"},
{"arrival_time" :"04:00","amount":"600","id":"FS"},
{"arrival_time" :"06:00","amount":"900","id":"JC"}];
bombombs
  • 593
  • 1
  • 13
  • It's an array, not an object. Searching "Remove element from array" will get you more useful results. – Bergi Jan 26 '22 at 19:29
  • I assume that you meant to say remove a `row` (rather, an element) from an Array. The `bank_data` you have shown in the question is an Array. Each element within that Array, though, is an object (with keys `arrival_time`, `amount`, `id`). – jsN00b Jan 26 '22 at 19:30
  • The problem with your function is that `splice` changes the array while you're iterating it. See the duplicate for more explanation and solutions. – Bergi Jan 26 '22 at 19:32
  • `bank_data = [...bank_data.filter(ob => bank_data[bank_data.length - 1] - ob.amount > 300)];` <-- please try this. It should get you the desired result. Kindly research as @Bergi has noted above. – jsN00b Jan 26 '22 at 19:34
  • "Best" in terms of performance? Removing/updating in the array is always performance inefficient. – Zain Ul Abideen Jan 26 '22 at 19:37

0 Answers0