Home > Software design >  Getting an empty array when removing objects from array
Getting an empty array when removing objects from array

Time:05-30

My array (this.serviceTable) includes an object, that looks like this:

[
    {
        "0": {
            "service": "Service 0"
        },
        "id": 0
    },
    {
        "1": {
            "service": "Service 1"
        },
        "id": 1
    },
    {
        "2": {
            "service": "Service 2"
        },
        "id": 2
    }
]

And from that array, I want to delete the following:

[
    {
        "2": {
            "service": "Service 2"
        },
        "id": 2
    },
    {
        "0": {
            "service": "Service 0"
        },
        "id": 0
    }
]

So the result should be:

[
    {
        "1": {
            "service": "Service 1"
        },
        "id": 1
    }
]

This is what I have tried:

const SELECTED_IDS:Array<number> = [];
for (let item of this.selection.selected) {
  SELECTED_IDS.push(item.id);
}

console.log(
  this.serviceTable.filter((serviceValue, i) => {
    !SELECTED_IDS.includes(i);
  }
), 'result');
}

But that returns an empty array.

CodePudding user response:

Your arrow function syntax is wrong. If you use curly brackets the function does not automatically return anything like it does without the curly brackets. And filter function expects that the function return a boolean.

See the docs.

Here is the correction:

console.log(
  this.serviceTable.filter((serviceValue, i) => !SELECTED_IDS.includes(i)
), 'result');

// OR

console.log(
  this.serviceTable.filter((serviceValue, i) => {
    return !SELECTED_IDS.includes(i);
  }
), 'result');
}

  • Related