1

I have an array that contains objects of weekdays that I want to filter by elements that contain null in "opens" or "closes" (Don't want them in my final array to exist).

let array = [
             [
               {"weekday":1,"opens":"09:00","closes":"11:00"}, 
               {"weekday":1,"opens":null,"closes":null}
             ],
             [
               {"weekday":2,"opens":"09:00","closes":"11:00"}, 
               {"weekday":2,"opens":"12:30","closes":"17:00"},
               {"weekday":2,"opens":"18:00","closes":"null"}
             ], ...
           ]

I would like to return a new created array so that I don't alter the original array.

My current solution looks like that but feels ugly

let newArray = [];

array.forEach( (day, index)  => {
    day = day.filter( timeblock => 
       timeblock.opens != null && timeblock.closes != null
    );
    newArray.push(day);
});

How can I filter nested arrays more elegant? (jsfiddle if needed: https://jsfiddle.net/2jukvsoy/1/)

1
  • What's wrong with the code you've got? Commented May 28, 2018 at 12:21

1 Answer 1

1
let newArray = array.map(day => 
    day.filter(timeblock => 
        timeblock.opens != null && timeblock.closes != null
    )
);
Sign up to request clarification or add additional context in comments.

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.