陣列物件的去重然後排序

李文楊發表於2018-03-04
    let arr = [
    {
        name: 'aaa',
        data: 20
    },{
        name: 'bbb',
        data: 10
    },{
        name: 'aaa',
        data: 20
    },{
        name: 'ccc',
        data: 2
    },{
        name: 'ddd',
        data: 31
    },{
        name: 'eee',
        data: 1
    },{
        name: 'fff',
        data: 4
    },
    ];
const sort = arr => {
        // 去重
        let obj = {};
        let newArr = [];
        arr.forEach((val) => {
            console.log(val);
            if(!obj[val.name]) {
                obj[val.name] = val;
                newArr.push(val);
            };
        });
        // 最簡單的使用sort去重
        let sortArr = newArr.sort((a, b) => {
            return a.data - b.data;
        });
        // 氣泡排序去重(ps:還有好多種自己慢慢試吧)
        //        for (let i = 0; i < newArr.length; i++) {
        //            for (let j = i+1; j < newArr.length; j++) {
        //                let curr = newArr[i];
        //                if (curr.data > newArr[j].data) {
        //                    let ind = newArr[j];
        //                    newArr[i] = ind;
        //                    newArr[j] = curr;
        //                };
        //            };
        //        };
        console.log(newArr);
    };
    sort(arr);

 

相關文章