Search code examples
javascriptjsonnode.jswatson

Function trims values after being passed in another function


I would like have renderData() display the values from max. When I console.log(max) in calculateData() it displays all three maximum values from three JSON objects. However, when I return max in renderData() it only shows the first value. Why is this, and what can I do to make it display all three values instead of just one? Note: data is the json list of objects being passed. Thank you!

function calculateData(data) {

    for (i in data) {

        var arr = [];
        var max;
        var obj = data[i].tones;

        obj.map(function(item) {
            var data = item.score;
            arr.push(data);
        })

        max = arr.reduce(function(a, b) {
            return Math.max(a, b);
        })

        //Returns an array containing dominant [emotion_tone, language_tone, social_tone]
        return renderData(max);
    }

}

function renderData(max) {
    console.log(max);
};

Solution

  • Maybe this is what you are intending? It will iterate through the entire data object calculating a max for each iteration, collect them in an array, and then finally call the renderData func with that array.

    function calculateData(data) {
       var maxes = [];
        for (i in data) {
    
            var arr = [];
            var max;
            var obj = data[i].tones;
    
            obj.map(function(item) {
                var data = item.score;
                arr.push(data);
            })
    
            maxes.push(arr.reduce(function(a, b) {
                return Math.max(a, b);
            }));
    
        }
        return renderData(maxes);
    
    }
    
    function renderData(max) {
        console.log(max);
    };