JQuery Javascript Sort Array by Highest Count

后端 未结 5 522
清酒与你
清酒与你 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:43

    I recently created a library with such a function.

    var items = {}, sortableItems = [], i, len, element,
        listOfStrings = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"];
    
    for (i = 0, len = listOfStrings.length; i < len; i += 1) {
        if (items.hasOwnProperty(listOfStrings[i])) {
            items[listOfStrings[i]] += 1;
        } else {
            items[listOfStrings[i]] = 1;
        }
    }
    
    for (element in items) {
        if (items.hasOwnProperty(element)) {
            sortableItems.push([element, items[element]]);
        }
    }
    
    sortableItems.sort(function (first, second) {
        return second[1] - first[1];
    });
    
    console.log(sortableItems);
    

    Output

    [ [ 'ABAB', 3 ], [ 'EFEF', 2 ], [ 'CDCD', 1 ] ]
    

提交回复
热议问题