js對數組分組處理


一、js數組分組

1.js對數據分組類似group by

源碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jquery 數組按某一字段分組</title>
    <!-- <script src="./Scripts/jquery-3.3.1.min.js"></script> -->
    <script src="./Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
    <script type="text/javascript">
     $(function()
     {
         let a = null;
         let aa = a?a:0;
         console.log(aa);
         let b = undefined;
         let bb = b?b:0;
         console.log(bb);
         let c = '';
         let cc = c?c:0;
         console.log(cc);

        list = [
        {"name": "John", "Average": 15, "High": 10, "DtmStamp": 1358226000000},
        {"name": "Jane", "Average": 16, "High": 92, "DtmStamp": 1358226000000},
        {"name": "Jane", "Average": 17, "High": 45, "DtmStamp": 1358226000000},
        {"name": "John", "Average": 18, "High": 87, "DtmStamp": 1358226000000},
        {"name": "Jane", "Average": 15, "High": 10, "DtmStamp": 1358226060000},
        {"name": "John", "Average": 16, "High": 87, "DtmStamp": 1358226060000},
        {"name": "John", "Average": 17, "High": 45, "DtmStamp": 1358226060000},
        {"name": "Jane", "Average": 18, "High": 92, "DtmStamp": 1358226060000}
        ];
        const sorted =groupBy(list, function (item) {
            return [item.name];//按照name進行分組
        });
        console.log(sorted);
     })
    function  groupBy(array, f) 
    {
        debugger;
        const groups = {};        
        array.forEach(function (o) { //注意這里必須是forEach 大寫
            const group = JSON.stringify(f(o));
            groups[group] = groups[group] || [];
            groups[group].push(o);
        });
        return Object.keys(groups).map(function (group) {
            return groups[group];
        }); 
    }    
    </script>
</body>
</html>

具體實現思路:

  • 1.函數groupBy有兩個形參,一為對象數組,二為匿名函數(該函數功能:返回對象的某個指定屬性的屬性值並存放在數組中);
  • 2.groupBy函數內,先創建一個空對象;
  • 3.然后forEach遍歷對象數組,遍歷時要執行的函數中只有一個形參o(數組中的每個元素);
  • 4.由於下面函數調用是想用name來分組,因此let group = JSON.stringify( f(o) ),相當於先獲取到對象數組list中的name屬性對應的屬性值並放入數組中:["John"],然后再將屬性值轉換為json字符串:'["John"]';
  • 5.groups[group] = groups[group] || [],在js中對象也是關聯數組,因此這里相當於做了兩件事,一是把group作為groups的key,二是將對應的value初始化,第一次執行為空數組,循環執行時找到相同的name時保持不變;
  • 6.groups[group].push( o ),這句相當於把list中每個對象壓入數組中作為value;
  • 7.最后,Object.keys(groups)是取出groups對象中的所有key,然后遍歷一個個key組成的新數組,返回分好了組的二維數組

2.js根據json數據中的某一個屬性來給數據分組

源碼如下:

 <!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<span id ="span" style="width: 50px;height: 200px;"></span>
	</body>
	<script>
	var arr = [{"Group":1,"Groupheader":"質量管理","Leftimg":"","Left":"","Min":"","Right":"","Rightimg":""},
{"Group":1,"Groupheader":"","Leftimg":"","Left":"","Min":"質量巡檢","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"設備管理","Leftimg":"","Left":"","Min":"","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"","Leftimg":"","Left":"","Min":"設備專業點檢","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"","Leftimg":"","Left":"","Min":"設備日檢","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"","Leftimg":"","Left":"","Min":"設備周檢","Right":"","Rightimg":""},
{"Group":2,"Groupheader":"","Leftimg":"","Left":"","Min":"設備月檢","Right":"","Rightimg":""}];
 
var map = {},
    dest = [];
for(var i = 0; i < arr.length; i++){
    var ai = arr[i];
    if(!map[ai.Groupheader]){
        dest.push({
            Groupheader: ai.Groupheader,      
            data: [ai]
        });
        map[ai.Groupheader] = ai;
    }else{
        for(var j = 0; j < dest.length; j++){
            var dj = dest[j];
            if(dj.Groupheader == ai.Groupheader){
                dj.data.push(ai);
                break;
            }
        }
    }
}
console.log(JSON.stringify(dest));
	var sapn = document.getElementById("span");
	span.innerHTML = JSON.stringify(dest);
	</script>
</html>

二、js數組排序
參考1:https://blog.csdn.net/shuoSmallWhite/article/details/89447418
參考2:https://blog.csdn.net/qq_24607837/article/details/83342585
總結如下:

/**
 * 數組排序:Desc:降序  Asc:升序
 * @param {any} property
 */
function arraySort(property,type) {
    return (firstobj, secondobj) => {
        const firstValue = firstobj[property];
        const secondValue = secondobj[property];
        switch (type) {
            case "Desc":
                return secondValue - firstValue; //降序
            case "Asc":
                return firstValue - secondValue; //升序
            default:
                return firstValue - secondValue; //升序
        }
    };
}


免責聲明!

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



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