Search code examples
javascriptloopssplice

splice inside a loop doesnt seem to be working


I am looping to a json object, where I have an array of objects. I want to remove from my array, the objects with a null value on iban and with more than 12 digits on Account number. If both this conditions are met, I want to remove the item. I have 3 items on my list that should be removed because those meet this conditions, yet only 2 are removed.

my function goes like this

for (var i = 0; i < benefs.length; i++) {
                var befNumberIban = benefs[i].Iban;
                var befNumber = benefs[i].AccountNumber;
  if (befNumber != null) {

    if (isBefLenght && (befNumberIban == null || befNumberIban == "")) {


        benefs.splice(i, 1);

I cant understand why it only removes 2 our 3 objects that meet the condition...something about splice?


Solution

  • from splice the array will re-indexed, so for the last item i will be 1 and array length will be 1 too it will not go inside the loop and hence you are not getting the desire result inside for loop. You can use the filter to achieve this easily.

    const benefs = [{
      Iban: null,
      AccountNumber: "",
    }, {
      Iban: null,
      AccountNumber: "",
    }, {
      Iban: null,
      AccountNumber: "",
    }]
    
    const isBefLenght = true;
    var newArray = benefs.filter(a => {
      return isBefLenght && !(a.Iban === null || a.befNumberIban === "");
    })
    
    console.log(newArray);