js對象數(shù)組按照另一個(gè)數(shù)組排序

場景
下拉列表有4個(gè)選項(xiàng)
用戶按照先后排序后保存
[2, 4, 1, 3]
保存完后,按照順序進(jìn)行排序

        let options = [{
            id: 1,
            name: '北京'
        }, {
            id: 2,
            name: '上海'
        }, {
            id: 3,
            name: '深圳'
        }, {
            id: 4,
            name: '杭州'
        }];

思路,兩個(gè)數(shù)組,排序有點(diǎn)困難
如果變成一個(gè)數(shù)組排序,就方便了

我們給每個(gè)option新增一個(gè)排序?qū)傩詓ordId
這個(gè)sordId的值就是 option的id在 showArr中的索引位置

        let showArr = [2, 4, 1, 3]
        options.forEach(item=>{
            let sortId = showArr.indexOf(item.id)
            item.sortId = sortId
        })

現(xiàn)在我們的options數(shù)組已經(jīng)可以排序了


圖片.png

再寫一個(gè)對象數(shù)組按照屬性名排序的方法

//按照prop屬性升序排序
    function sort(prop) {
      return function (obj1, obj2) {
        var val1 = obj1[prop]
        var val2 = obj2[prop]
            if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
                val1 = Number(val1)
                val2 = Number(val2)
            }
            if (val1 < val2) {
                return -1
            } else if (val1 > val2) {
                return 1
            } else {
                return 0
            }
        }
    }
    let options = [{
        id: 1,
            name: '北京'
        }, {
            id: 2,
            name: '上海'
        }, {
            id: 3,
            name: '深圳'
        }, {
            id: 4,
            name: '杭州'
        }];
        let showArr = [2, 4, 1, 3]
        options.forEach(item=>{
            let sortId = showArr.indexOf(item.id)
            item.sortId = sortId
        })
        let sortArr = options.sort(sort('sortId'))
        console.log(sortArr)

最后輸出


圖片.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容