Skip to content
Advertisement

How to not show empty sub-objects in a js array

I have my data set, and I was been able to filter it by EmployeeId from mine subobject. However, I don’t want to filter those empty objects that theirs subobjects GroupedServices does not contain any items (length is 0) Here is my working example: https://jsfiddle.net/sko3y1vq/6/

JavaScript
JavaScript

Thanks

Advertisement

Answer

Use Arry.prototype.reduce:

  • Reduce an Array to a subset Array
  • push to the accumulator array only if GroupedServices.length > 0
JavaScript

Here’s a jsFiddle demo


To conclude, there’s no need to iterate twice the same array, first using .map() and than using .filter(). That’s why .reduce() is the best choice for such a task: creating a subset Array in one go.

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