Skip to content
Advertisement

How to get Main Array with the Object when filtering a Sub array

I have this array of data, where when I filter the sub-array the orderedItems object key is only filtered not the whole data, This is my code.

JavaScript

Result:

JavaScript

Expected Result:

JavaScript

The filter works but only for the orderedItems object key, I wanted the id too outside of the array to be filtered too. Is there any way to do this?, If there any clarification or explanation you need please comment down below. Thanks

Advertisement

Answer

You can use Array#reduce to iterate over the list and in each iteration, compute the filtered orders of the current item, and in case it’s not empty, add it to the accumulator with the current id:

JavaScript

Another way to complete your approach would be to filter the resulting list by the length of orderedItems:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement