Search code examples
javascriptarraysmultidimensional-arrayfiltersplice

Delete element in multidimensional array when a property of that element is empty


Hey I am trying to delete an element in a multidimensional array,when his array property "texts" is empty. The approach I am trying is with the filter method like so:

array.filter(item => item.texts.length === 0)

But for some reason it's not working. Other way would be to find the element by it's name property (which I have access), get its index, check if the texts array inside it is empty and use the splice method to delete it, but I am not sure how to do that in a multidimensional array. Any help would be appreciated.

This is the array I am dealing with:

const array = [
 0: Object {
  name: 'Name 1',
  texts[
   0: Obj{
    id: '123',
    body: 'test message'
   },
   1: Obj{
    id: '456',
    body: 'test message 2'
   }
  ]
 },

 1: Object {
  name: 'Name 2',
  texts[
   0: Obj{
    id: '789',
    body: 'test message3'
   },
   1: Obj{
    id: '101112',
    body: 'test message 4'
   }
  ]
 }
]

Solution

  • You need to make sure your Object is correctly declared, and then reverse the logic.

    array.filter(item => item.texts.length !== 0)
    

    const array = [
      {
        name: 'Name 1',
        texts: [
          {
            id: '123',
            body: 'test message'
          },
          {
            id: '456',
            body: 'test message 2'
          }
        ]
      },
      {
        name: 'Name 2',
        texts: []
      }
    ]
    
    console.log(array.filter(item => item.texts.length !== 0));