Home > Software engineering >  JS - Filtering nested array
JS - Filtering nested array

Time:08-25

is in JS any way to filter nested array values?

The desired result is to filter null values in nested array.

I tried the code below, but it is not correct.

const test = [
  [
    null,
    {
        "start_time": "2022-08-25T08:45:00.000Z",
        "end_time": "2022-08-25T09:45:00.000Z"
    },
    null,
    null,
    null,
    null,
    {
        "start_time": "2022-08-25T10:00:00.000Z",
        "end_time": "2022-08-25T11:00:00.000Z"
    },
  ]
]

let arr = test.filter(item => {
  return item != null;
})

console.log(arr);

CodePudding user response:

You can use Array#map before Array#filter as follows:

const test = [
  [
    null,
    {
        "start_time": "2022-08-25T08:45:00.000Z",
        "end_time": "2022-08-25T09:45:00.000Z"
    },
    null,
    null,
    null,
    null,
    {
        "start_time": "2022-08-25T10:00:00.000Z",
        "end_time": "2022-08-25T11:00:00.000Z"
    },
  ]
]

const arr = test.map(
    items => items.filter(item => {
      return item !== null;
    })
);

console.log(arr);

CodePudding user response:

Of course, you can reduce the amount of code

const test = [[null,{"start_time": "2022-08-25T08:45:00.000Z","end_time": "2022-08-25T09:45:00.000Z"},null,null,null,null,{"start_time": "2022-08-25T10:00:00.000Z","end_time": "2022-08-25T11:00:00.000Z"}]];

const arr = test.map(e => e.filter(Boolean));

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related