1

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);
1
  • What is your desired result? Commented Aug 24, 2022 at 23:11

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.