Search code examples
javascriptarrayslodash

Fallback value required for if array returns 0 values


I'm calculating a minimum value for the base of a graph output. One of my arrays are outputting a zero value thus not meeting the requirement and returning undefined.

const data =  [
    {value:0},
    {value:0},
    {value:0} ];

const defaultMinThreshold = 0;

const minThreshold = _.min([parseFloat(_.minBy(_(data).filter(d => d.value > 0).value(), 'value').value) - 0.5, defaultMinThreshold]);

If the data had any value larger than 0 e.g.

const data =  [
    {value:1},
    {value:0},
    {value:0} ];

This returns minThreshold as 0 - which is expected. I need it to return 0 instead of returning undefined when/if all the values are 0.

I need to put a conditional in that searches data for values that at least has 1 value larger than 0 else return 0 by default.

JS Fiddle - https://jsfiddle.net/0cps7q9j/

n.b As you can see I do filter the values to be > 0, I could do a >= 0 but this lowers the base to 0 for arrays that could have a zero value in that data set so can't change this.

Reason for the filter is if the data had values of

const data =  [
        {value:4},
        {value:4},
        {value:3} ];

With above the minimum value would return 3, so the threshold would be 3 and the graph would start from 3 rather than zero.


Solution

  • If you don't have to completely use Lodash, here is something that is functional and readable. You could probably transform this into a pure Lodash solution as well if you like.

    https://jsfiddle.net/0cps7q9j/11/

    const data =  [
        {value:-1},
        {value:'0'},
        {value:1.234} ];
    
    const defaultMinThreshold = 0;
    
      const filteredDataValueArray = data.filter(obj => !isNaN(parseFloat(obj.value)) && parseFloat(obj.value) >= 0).map(obj => obj.value);
    
        const minThreshold = _.min(filteredDataValueArray) || defaultMinThreshold;
    
    console.log('filteredDataValueArray', filteredDataValueArray);
    console.log('minThreshold', minThreshold);