JQuery Javascript Sort Array by Highest Count

后端 未结 5 523
清酒与你
清酒与你 2021-01-23 06:54

I have:

myArray = [\"ABAB\", \"ABAB\", \"ABAB\", \"CDCD\", \"EFEF\", \"EFEF\"]

I need to count by occurrences and sort by highest count. This w

5条回答
  •  清歌不尽
    2021-01-23 07:28

    Try this:

    array_elements = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];
    
    var result_array = [];
    
    var current = null;
    var cnt = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != current) {
            if (cnt > 0) {
                result_array.push([current,cnt]);
            }
            current = array_elements[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        result_array.push([current,cnt]);
    }
    
    result_array.sort(function(x,y) {return y[1] - x[1]})
    alert(result_array);
    

    The result_array will have the result.

提交回复
热议问题