使用JavaScript按字母顺序对数据进行排序

时间:2018-11-30 09:26:39

标签: javascript

我正在尝试对这段代码显示的类别进行排序。有人知道怎么做吗?它读取具有以下结构的JSON文档:

`"id" = "test" 
"question" = "test" 
"answer" = "test" 
"category" = "test"`

所有类别必须按字母顺序显示。示例中的类别为“苏打”,“苹果”和“猫”。预先感谢。

enter image description here

function sortByCategory(data) {
                    return data.reduce((obj, c) => {
                        const { category, ...rest } = c;
                        obj[category] = obj[category] || [];
                        obj[category].push(rest);
                        return obj;
                    }, {});
                }

                // Returns the question/answer HTML 
                function buildQuestionHTML(arr) {

                    // Iterate over the category array objects
                    return arr.map(el => {

                        // In each case return the question/answer HTML
                        return `
                  <li class="block">
                    <a class="cd-faq-trigger" href="${el.id}">${el.question}</a>
                    <div class="cd-faq-content">
                      <p>${el.answer}</p>
                    </div> 
                  </li>
                `

                        // Making sure we join up the final array
                    }).join('');
                }

                // Returns all the HTML from the categorised data
                function buildPageHTML(data) {

                    // Iterate over the categorised data
                    return Object.keys(data).reduce((acc, c) => {

                        // Get the question/answer HTML
                        const questionHTML = buildQuestionHTML(data[c]);

                        // Create the scaffold for the category and
                        // add the category name, and question/answer HTML
                        const html = `
                  <li id="${c}" class="cd-faq-title">
                    <h2>${c}</h2>
                  </li>
                  ${questionHTML}
                `;
                        acc.push(html);
                        return acc;

                        // We're adding the HTML to an array so we need
                        // to ensure we join it up into a string
                    }, []).join('');
                }

                function displayQuestions() {

                    // Get the data
                    // This would normally be a call to your server which 
                    // would return some JSON data
                    $.getJSON("/json.json", function (data) {

                        // create a string of the object 
                        data = JSON.stringify(data);

                        // Parse the data
                        const questions = JSON.parse(data);

                        // Sort the data by category
                        const categoryData = sortByCategory(questions);

                        // Get the root element where you want the compiled data to be added
                        const root = document.getElementById('algemeen');

                        // Build the HTML
                        const html = buildPageHTML(categoryData);

                        // Add it to the root element
                        root.insertAdjacentHTML('beforeend', html);


                    });
                }

                // call displayQuestions
                displayQuestions();
<!doctype html>
            <html lang="en" class="no-js">
            
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
                <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
                <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
                <link rel="stylesheet" href="css/reset.css"> <!-- CSS reset -->
                <link rel="stylesheet" href="css/style.css"> <!-- Resource style -->
                <script src="js/modernizr.js"></script> <!-- Modernizr -->
                <script src="js/alerts.js"></script> <!-- Many Alerts -->
                <title>FAQ</title>
            </head>
            
            <div class="navbar">
                <a href="#"><img class="" src="images/.png"></a>
                <div class="navbar-right">
                    <a href="-"><img
                            class="language" src="images/.png"></a>
                </div>
            </div>
    <body>
       <section class="cd-faq">
            <ul class="cd-faq-categories" id="onderwerp">
    
            </ul> <!-- cd-faq-categories -->
    
<ul id="algemeen" class="cd-faq-group">
            </ul>
    </section> <!-- cd-faq -->
    
        <script src="js/jquery-2.1.1.js"></script>
        <script src="js/jquery.document.custom.min.js"></script>
        <script src="js/main.js"></script> <!-- Resource jQuery -->
    
    </body>
    
    </html>

将JS代码的信用提供给@Andy。

1 个答案:

答案 0 :(得分:1)

这应该可以帮助您按字母顺序对类别进行排序:

// function to sort categories alphabetically
// place this function inside your JavaScript file where you have written all your code
function sortCategoriesAlphabetically(data) {
    return Object.keys(data).sort().reduce((accumulator, currentValue) => {
        accumulator[currentValue] = data[currentValue];
        return accumulator;
    }, {});
}

// the following two lines are part of your **displayQuestions** function
// Sort the data by category (already written by you)
let categoryData = sortByCategory(questions);

// Sort categories alphabetically (to be added below the above line)
categoryData = sortCategoriesAlphabetically(categoryData);