陣列及陣列物件操作 ----------包括排序,去重,合併,翻轉等

Caiyun6666發表於2020-11-05

1.陣列物件根據某一屬性值排序

 let arr=[
 {id:4,name:大大},
{id:1,name:輕輕},
{id:2,name:文文},
]
  function sortRule(a,b) {
                return a.id-b.id; 
            }
  arr.sort(sortRule);//直接改變原陣列

2.陣列去重

let arr = [1,0,0,2,9,8,3,1];

         function unique(arr) {
             return Array.from(new Set(arr))
  }
    console.log(unique(arr));   // [1,0,2,9,8,3]

3.陣列物件去重

           function unique(arr){
                var hash = [];
                for(var i=0;i<arr.length;i++){
                    var flag = true;
                    for(var j=0;j<hash.length;j++){
                        if(arr[i].province_name == hash[j].province_name){
                            flag = false;
                        }
                    }
                    if(flag){
                        hash.push(arr[i]);
                    }
                }
                return hash;
            }
this.allShengData = unique(this.allShengData);

4.陣列物件合併

data.data.data如圖
在這裡插入圖片描述

let tempArr = [];
                        let aa = [];
                        for (let i = 0; i < data.data.data.length; i++) {
                            if (tempArr.indexOf(data.data.data[i].hospital_id) === -1) {
                                aa.push({
                                    id: data.data.data[i].hospital_id,
                                    label: data.data.data[i].hospital_name,
                                    children: [
                                        {id: data.data.data[i].doctor_id,
                                        label: data.data.data[i].doctor_name,
                                        disabled: false
                                        }],
                                    disabled: true
                                });
                                tempArr.push(data.data.data[i].hospital_id);
                            } else {
                                for (let j = 0; j < aa.length; j++) {
                                    if (aa[j].id == data.data.data[i].hospital_id) {
                                        aa[j].children.push(
                                            {
                                                id: data.data.data[i].doctor_id,
                                                label: data.data.data[i].doctor_name,
                                                disabled: false
                                        });
                                        break;
                                    }
                                }
                            }
                        }
                        // console.log(aa);
                        this.doData=aa

合併渲染後在這裡插入圖片描述5.陣列翻轉

var arr = ["f","e","i","e","s","o","f","t"];
document.writeln(arr.join()); f,e,i,e,s,o,f,t

arr.reverse();
document.writeln(arr.join()); t,f,o,s,e,i,e,f

相關文章