js中json對象數組按對象屬性排序---1


轉載:https://www.cnblogs.com/jasonwang2y60/p/6656103.html

在實際工作經常會出現這樣一個問題:后台返回一個數組中有i個json數據,需要我們根據json中某一項進行數組的排序。

例如返回的數據結構大概是這樣:

   {
    result:[
      {id:1,name:'中國銀行'},
      {id:3,name:'北京銀行'},
      {id:2,name:'河北銀行'},
      {id:10,name:'保定銀行'},
      {id:7,name:'淶水銀行'}
    ]
   } 

 

現在我們根據業務需要,要根據id的大小進行排序,按照id小的json到id大的json順序重新排列數組的順序

在js中添加排序的方法:

這里使用JavaScript sort() 方法,首先解釋下這個sort的方法

語法:arrayObject.sort(sortby)            sortby:可選,規定排序順序。必須是函數。

如果調用該方法時沒有使用參數,將按字母順序對數組中的元素進行排序,說得更精確點,是按照字符編碼的順序進行排序。要實現這一點,首先應把數組的元素都轉換成字符串(如有必要),以便進行比較。

如果想按照其他標准進行排序,就需要提供比較函數,該函數要比較兩個值,然后返回一個用於說明這兩個值的相對順序的數字。比較函數應該具有兩個參數 a 和 b,其返回值如下:

  • 若 a 小於 b,在排序后的數組中 a 應該出現在 b 之前,則返回一個小於 0 的值。
  • 若 a 等於 b,則返回 0。
  • 若 a 大於 b,則返回一個大於 0 的值。

 

下面開始使用sort(sortby) 來進行這個排序,並打印到控制台:

    function sortId(a,b){  
       return a.id-b.id  
    }
    result.sort(sortId);
    console.log(result); 

然后查看控制台,排序成功:

 

附: 前端機試題一個(對數據進行排序)

 

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body, html {
            padding: 0;
            margin: 0;
            font-size: 14px;
            color: #000000;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            table-layout: fixed;
        }

        thead {
            background: #3d444c;
            color: #ffffff;
        }

        td, th {
            border: 1px solid #e1e1e1;
            padding: 0;
            height: 30px;
            line-height: 30px;
            text-align: center;
        }

        .sort-asc::after,
        .sort-desc::after {
            content: ' ';
            display: inline-block;
            margin-left: 5px;
            vertical-align: middle;

        }
        .sort-asc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid #eee;
        }
        .sort-desc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-top: 4px solid #eee;
        }
    </style>
</head>
<body>
<table>
    <thead id="jsHeader">
    <tr>
        <th>product</th>
        <th>price</th>
        <th>sales</th>
    </tr>
    </thead>
    <tbody id="jsList">
    <tr>
        <td>1</td>
        <td>10.0</td>
        <td>800</td>
    </tr>
    <tr>
        <td>2</td>
        <td>30.0</td>
        <td>300</td>
    </tr>
    <tr>
        <td>3</td>
        <td>20.5</td>
        <td>100</td>
    </tr>
    <tr>
        <td>4</td>
        <td>40.5</td>
        <td>200</td>
    </tr>
    <tr>
        <td>5</td>
        <td>60.5</td>
        <td>600</td>
    </tr>
    <tr>
        <td>6</td>
        <td>50.0</td>
        <td>400</td>
    </tr>
    <tr>
        <td>7</td>
        <td>70.0</td>
        <td>700</td>
    </tr>
    <tr>
        <td>8</td>
        <td>80.5</td>
        <td>500</td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    /**
     *  請完成 sortData 函數,根據參數的要求對表格所有行進行重新排序。
     *  1、type為product、price或者sales,分別對應第1 ~ 3列
     *  2、order為asc或者desc,asc表示升序,desc為降序
     *  3、例如 sortData('price', 'asc') 表示按照price列從低到高排序
     *  4、所有表格內容均為數字,每一列數字均不會重復
     *  5、不要使用第三方插件
     */
    function sortData(type, order) {
        //完成您的代碼

        if(order == 'asc'){
            data.sort( (a, b)=> a[type] - b[type] );
        }else if(order == 'desc'){

            data.sort( (a, b)=> b[type] - a[type] );
        }

        //調用渲染視圖
        render(data);
        
    }

    //渲染視圖

    function render(data) {
        let tbodyHTML = '';
        for( let i = 0; i < data.length; i++ ){
            tbodyHTML += ` <tr>
                                <td>${data[i].product}</td>
                                <td>${data[i].price}</td>
                                <td>${data[i].sales}</td>
                            </tr>`
        }

        document.getElementById('jsList').innerHTML = tbodyHTML;
    }



    //獲取數據
    let oTbody = document.getElementById('jsList');
    let oTr = oTbody.getElementsByTagName('tr');

    let data = [];

    for(let i = 0; i < oTr.length; i++){
        data[i] = {
            product: oTr[i].getElementsByTagName('td')[0].innerText,
            price: oTr[i].getElementsByTagName('td')[1].innerText,
            sales: oTr[i].getElementsByTagName('td')[2].innerText,
        }
    }


    /* 原數據格式
       [
    *   {product: "1", price: "10.0", sales: "800"},
    *   {product: "2", price: "30.0", sales: "300"},
    *   {product: "3", price: "20.5", sales: "100"},
    *   {product: "4", price: "40.5", sales: "200"},
    *   {product: "5", price: "60.5", sales: "600"},
    *   {product: "6", price: "50.0", sales: "400"},
    *   {product: "7", price: "70.0", sales: "700"},
    *   {product: "8", price: "80.5", sales: "500"}
    *  ]
    * */



    //sortData('product', 'desc');
    //調用排序函數
    sortData('price','desc')




    //sortData('product', 'desc');

</script>
</body>
</html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM