前端宝典

一、排序

1.根据对象内某一属性进行排序(过滤掉字符串,数值相比较排序)

const obj = [
    {
        pointName: '1幢',
        pointId: '1024',
    },
    {
        pointName: '4幢',
        pointId: '1014',
    },
    {
        pointName: '2幢',
        pointId: '1004',
    },
    {
        pointName: '3幢',
        pointId: '1024',
    },
];
const sortBuildName = (property) => {
    return (a, b) => {
          const value1 = a[property].substr(0, a[property].length - 1);
          const value2 = b[property].substr(0, b[property].length - 1);
          return value1 - value2;
      };
};
obj.sort(sortBuildName('pointName'));

排序前


排序前

排序后


排序后

2.不传参,将按照字符编码进行排序
const arr = ['General','Tom','Bob','John','Army'];
arr.sort();

输出:
image.png

const arr2 = [30,10,111,35,1899,50,45];
arr2.sort();

输出:
image.png

3.传入参数,实现升序/降序排序
const arr3 = [30,10,111,35,1899,50,45];
arr3.sort((a, b) => {
  return a -b;
})

输出:
image.png
const arr4 = [30,10,111,35,1899,50,45];
arr4.sort((a, b) => {
  return b - a;
})

输出:
image.png

4.根据数组中的对象的多个属性值排序,双重排序

const jsonStudents = [
    {name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
    {name:"LiLei", totalScore:"185", Chinese:"88", math:"97"},
    {name:"XiaoMing", totalScore:"196", Chinese:"96",math:"100"},
    {name:"Jim", totalScore:"196", Chinese:"98",math:"98"},
    {name:"Joy", totalScore:"198", Chinese:"99",math:"99"}];
jsonStudents.sort(function(a,b){
    var value1 = a.totalScore,
        value2 = b.totalScore;
    if(value1 === value2){
        return b.Chinese - a.Chinese;
    }
    return value2 - value1;
});

输出:
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容