JS-对象数组排序

题目—对象数组排序

题目描述:编写函数使得下面对象数组可根据age(age相同使用commentum排序)来进行降序排序并返回新数组

输入数据:
[{name:'JavaScript',age:24,commentnum:699},
{name:'Java',age:24,commentnum:698},
{name:'C++',age:29,commentnum:692},
{name:'C#',age:27,commentnum:694}]
输出数据:
[{name:'C++',age:29,commentnum:692},
{name:'C#',age:27,commentnum:694},
{name:'JavaScript',age:24,commentnum:699},
{name:'Java',age:24,commentnum:698},]

解题代码1

function ageSort(data) {
            //使用sort排序
            data.sort((a, b) => b.age == a.age ? b.commentnum - a.commentnum : b.age - a.age);
            return data;
        };

解题代码2

function ageSort(data) {
//使用冒泡排序算法
            for (let i = 0; i < data.length; i++) {
                for (let j = i + 1; j < data.length; j++) {
                    if (arr[i].age === arr[j].age) {
                        if (arr[i].commentnum < arr[j].commentnum) {
                            [arr[i], arr[j]] = [arr[j], arr[i]]
                        }
                    } else {
                        [arr[i], arr[j]] = [arr[j], arr[i]]
                    }
                }
            }
            return data;
        }

你可能感兴趣的:(javascript,数据结构,javascript,前端)