0

I have below code where I need to do sorting by underscore JS based on value of (y).

Please find my code below. I am trying to do ascending first and then reverse. Unfortunately, it is not doing the sorting at all for me and shows data without sorting.

        function getMessageNames(){
        var rowIter = 1;
        //document.getElementById("demo2").innerHTML += "from getMessageNames="+calltypes;
        for (var i in calltypes){
            keyId = calltypes[i].label;
            for (var index in keyMsgNames){
                if(keyMsgNames[index].Id == keyId){
                    var row = {"label":keyMsgNames[index].Name,"y":calltypes[i].y};
                    messageNames.push(row);
                    break;
                }
            }


// Result: 
//document.getElementById("demo2").innerHTML += "descending="+descending;
        }

            var ascending = _.sortBy(messageNames, ['y']); 
// Then get DESC 
var descending = ascending.reverse(); 
        for (var index in descending){
            addRow("CallTable", [ descending[index].label, descending[index].y], rowIter++);
        }
        createChart(descending,"Distribution on Key Messages",chartContainer);
    }

function createChart(data,title,container){
    var chart = new CanvasJS.Chart(container, {
                animationEnabled: true,
                title: {
                    text: title
                },
                data: [{
                    type: "pie",
                    startAngle: 240,
                    yValueFormatString: "",
                    indexLabel: "{label} '('{y}')'",
                    dataPoints: data
                }]
            });
            chart.render();
}

 function addRow(tblName, colData, rowNum){
    var table = document.getElementById(tblName);
    var tableRow = table.insertRow(rowNum);

    for (var index in colData){
        var cell = tableRow.insertCell(index);
        cell.innerHTML = colData[index];
    }
}

1 Answer 1

2

the sortBy expects an array of properties

Replace

var ascending = _.sortBy(messageNames, 'y'); 

with

var ascending = _.sortBy(messageNames, ['y']); 
Sign up to request clarification or add additional context in comments.

2 Comments

this is the answer. look at the _.underscore documentation _.sortBy(list, iteratee, [context])
I have placed it in above format. But when I use descending to show on html it is not working. Please find modified code above. It shows data as [6,6,7,6].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.