如何在JavaScript中按字母顺序(升序和降序)排序

时间:2018-09-25 02:34:27

标签: javascript arrays sorting tabletop.js

HTML:

<section class="cd-gallery">
    <ul id="courses">
    </ul>
    <div class="cd-fail-message">No results found</div>
</section>

<ul>
    <li><input id="buttonaz" type="button" value="Course name(a-z)"/></li>
    <li><input id="buttonza" type="button" value="Course name(z-a)"/></li>
    <li><input id="buttonlu" type="button" value="Last updated"></li>
<ul>

JavaScript:

var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/..."

function init() {
    Tabletop.init( { key: public_spreadsheet_url,
                   callback: showInfo,
                   simpleSheet: true } );
}
window.addEventListener('DOMContentLoaded', init);

function sortAZ(a, b) {
    var x = a.Course.toLowerCase();
    var y = b.Course.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortZA(a, b) {
    var x = a.Course.toLowerCase();
    var y = b.Course.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function showInfo(data) {
    var bodyContent = '';
    var sheetUrlRoot = 'https://docs.google.com/spreadsheets/d/';
    var buttonaz = document.getElementById("buttonaz");
    var buttonza = document.getElementById("buttonza");
    console.log(data)

    for (var i = 0; i < data.length; i++) {
        var sheetUrl = sheetUrlRoot + data[i].ActionId;
        var c = data[i].Course;
        var courseName = '<div class=\"courseName\">' + c + '</div>';
        var designer = data[i]['Designer'].toLowerCase();
        var numHolds = data[i]['On Hold']

        if (numHolds > 0) {
            bodyContent += '<li class="color-2 course mix ' + designer + ' "style="background-color: #E89696";>' + courseName + statusList+ sheetLink+ '</li>';
        } else if (numHolds <= 0){
            bodyContent += '<li class="color-1 course mix ' + designer + ' "style="background-color: #C2D5BE";>' + courseName + statusList+ sheetLink+'</li>';
        }
    }
    document.getElementById('courses').innerHTML = bodyContent;
    document.getElementById('buttonaz').onclick = data.sort(sortAZ);
    document.getElementById('buttonaz').onclick = data.sort(sortZA);
}

Hi Stack Overflow用户, 我已使用tabletop.js导入数据以显示我的大学手头的一组课程。但是,当单击按钮“课程名称(a-z)”和“课程名称(z-a)”时,我无法显示按字母顺序从a-z以及从z-a排序的课程。首次加载页面时显示数据,但是单击排序按钮时不会执行任何操作。

请帮助,我们将不胜感激!

P.S。我还使用mixitup jQuery插件按设计者的名称过滤课程。

3 个答案:

答案 0 :(得分:1)

请参阅具有两个按钮的代码,一个用于排序aZ,另一个用于排序Za。点击展开代码段,您将看到两个按钮,点击它们并享受排序

cols = 3
seps = ' ' * (cols - 1) + '\n'
with open("output.txt", "w") as f:
    for i, (k, v) in enumerate(dict_cols.items()):
        sep = '' if i == len(dict_cols) - 1 else ',' + seps[i % cols]
        f.write(v + sep)

如果传入数据是数组,请使用内置于sort()函数的javascript对数据进行排序

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort the array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort Az</button>
<button onclick="myFunction2()">Sort zA</button>
<p id="demo"></p>
<script>
var points = ["z", "b", "d", "a"];
var data1=Array.prototype.slice.call(points);
console.log('Za Sort ',data1.sort().reverse());
document.getElementById("demo").innerHTML = points;    

function myFunction1() {
    points.sort();
    document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
    
    document.getElementById("demo").innerHTML = data1.sort().reverse();
}
</script>
</body>
</html>

答案 1 :(得分:0)

这是在javascript中对某些数组进行排序的函数,具体取决于您如何应用它,并考虑到代码段:

//Sort alphabetically and ascending:

var myarray=["Bob", "Bully", "Amy"];

myarray.sort();

// Array now becomes ["Amy", "Bob", "Bully"]

现在让我们做相反的事情:

///按字母顺序和降序排列:

var myarray = [“ Bob”,“ Bully”,“ Amy”]

myarray.sort()

myarray.reverse()//数组现在变为[“ Bully”,“ Bob”,“ Amy”]

答案 2 :(得分:0)

如果您要使用库https://underscorejs.org/#

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');