javascript中对一个对象数组按照对象某个属性进行排序

需求:对timelist排序 安装keys 。

分析:timelist 是个数组对象,里面包含属性 keys,val。这里借助数组sort方法 传入function

    <script>
        //模拟数据源
        var timeList = [{
            keys: 1,
            val: "12点"
        }, {
            keys: 3,
            val: "24(0)"
        }, {
            keys: 2,
            val: "6点"
        }, {
            keys: 4,
            val: "18点"
        }, {
            keys: 0,
            val: "18点"
        }];
        //这里使用x[field], 而不使用x.field  防止x没有field属性 而报错 
        function sortBy(field) {
            return (x, y) => {
                return x[field] - y[field];
            }
        }
        timeList.sort(sortBy("keys"));

        //最后的结果
        var newTime = [];
        timeList.forEach((x) => {
            newTime.push(x.val);
        });
    </script>

资料:https://www.tangshuang.net/2406.html

https://www.w3school.com.cn/js/js_array_sort.asp

原文地址:https://www.cnblogs.com/y112102/p/11274457.html