Skip to content
Advertisement

How do I fix empty property values in an array of objects with different value type in javascript?

I have an array of objects returned from database. Goal is to calculate the percentage of marks for each id. For some objects marks are stored in array whereas for some it is just a normal variable.

JavaScript

the above code generates the following output

JavaScript

Percentage of marks for the penultimate object just returns an empty array. I tried getting the typeof marks but it returns object for both array and non array. How do I fix this?

Advertisement

Answer

You can standardised the marks to array by checking if marks is array using Array.isArray() and convert number to array. Then you can use your existing logic.

JavaScript

You can also use functional style to accomplish it.

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