首页 > 编程开发 > JavaScript    日期:2020-05-27 / 来自互联网 / 浏览

本文实例讲述了JS实现json数组排序操作。分享给大家供大家参考,具体如下:

有时需要根据json对象的某个属性排序json数组,javascript端有sort这个函数,具体可以参考:http://www.w3school.com.cn/jsref/jsref_sort.asp

我们可以传入一个对比函数,我实现了两个:一个降序排列,一个升序排列

/**
 * json对象数组按照某个属性排序:降序排列
 * @param {Object} propertyName
 */
function compareDesc(propertyName) {
  return function(object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if(value2 < value1) {
      return -1;
    } else if(value2 > value1) {
      return 1;
    } else {
      return 0;
    }
  }
}
/**
 * json对象数组按照某个属性排序:升序排列
 * @param {Object} propertyName
 */
function compareAsc(propertyName) {
  return function(object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if(value2 < value1) {
      return 1;
    } else if(value2 > value1) {
      return -1;
    } else {
      return 0;
    }
  }
}

例子:

var students=[{name:"hhhh",age:16},{name:"ggggg",age:17},{name:"dsdsad",age:18}];
students.sort(compareDesc("age"));  //按照年龄降序排列
console.log(students);

运行结果:

JS实现json数组排序操作实例分析

var students=[{name:"hhhh",age:16},{name:"ggggg",age:17},{name:"dsdsad",age:18}];
students.sort(compareAsc("age"));  //按照年龄升序排列
console.log(students);

运行结果:

JS实现json数组排序操作实例分析

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章