我有一个JavaScript对象数组:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

如何在JavaScript中按last_nom的值对它们进行排序?

我知道排序(a,b),但这似乎只适用于字符串和数字。是否需要向对象添加toString()方法?


当前回答

对于工作狂:

const objectSorter = (p) => (a, b) => ((a, b) => a>b ? 1 : a<b ? -1 : 0)(a[p], b[p]);
objs.sort(objectSorter('first_nom'));

其他回答

我遇到了排序对象数组的问题,改变了值的优先级。基本上,我想按年龄,然后按姓氏,或者仅仅按姓氏,名字来对一系列人进行排序。

我认为与其他答案相比,这是最简单的解决方案。

它用于调用sortPeoples(['array','of','properties'],reverse=false)。

///////////////////////人群示例阵列///////////////////////var人民=[{姓名:“Zach”,姓:“Emergency”,年龄:1},{姓名:“南希”,姓:“护士”,年龄:1岁},{姓名:“Ethel”,姓:“Emergency”,年龄:1},{姓名:“尼娜”,姓:“护士”,年龄:42岁},{姓名:“Anthony”,姓:“Emergency”,年龄:42岁},{姓名:“尼娜”,姓:“护士”,年龄:32岁},{姓名:“Ed”,姓:“Emergency”,年龄:28岁},{姓名:“彼得”,姓:“医生”,年龄:58岁},{姓名:“Al”,姓:“Emergency”,年龄:58岁},{姓名:“Ruth”,姓:“Registration”,年龄:62岁},{姓名:“Ed”,姓:“Emergency”,年龄:38岁},{姓名:“Tammy”,姓:“Triage”,年龄:29岁},{姓名:“Alan”,姓:“Emergency”,年龄:60岁},{姓名:“尼娜”,姓:“护士”,年龄:58岁}];////////////////////////排序功能/////////////////////函数sortPeoples(propertyArr,reverse){函数比较(a,b){变量i=0;while(propertyArr[i]){如果(a[propertyArr[i]]<b[propertyAr[i]])返回-1;如果(a[propertyArr[i]]>b[propertyAr[i]])返回1;i++;}返回0;}人民。排序(比较);if(反向){peoples.reverse();}};////////////////排序方法结束///////////////函数printPeoples(){$(“#输出”).html(“”);people.forEach(功能(人){$('#output').append(person.surname+“”+person.name+““”+person.age+“<br>”);})}<head><script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script></head><html><body><button onclick=“sortPeoples(['surname']);printPeoples()”>仅按姓氏ASC排序会导致同名案例的混乱</button><br><button onclick=“sortPeoples(['surname','name],true);printPeoples()”>按姓氏排序,然后按名称DESC</button><br><button onclick=“sortPeoples(['age']);printPeoples()”>按age ASC排序。与第一种情况相同的问题</button><br><button onclick=“sortPeoples(['age','姓']);printPeoples()”>按age和姓氏ASC排序。添加第二个字段修复了它。</button><br><div id=“output”></div></body></html>

使用原型继承简单快速地解决此问题:

Array.prototype.sortBy = function(p) {
  return this.slice(0).sort(function(a,b) {
    return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
  });
}

示例/用法

objs = [{age:44,name:'vinay'},{age:24,name:'deepak'},{age:74,name:'suresh'}];

objs.sortBy('age');
// Returns
// [{"age":24,"name":"deepak"},{"age":44,"name":"vinay"},{"age":74,"name":"suresh"}]

objs.sortBy('name');
// Returns
// [{"age":24,"name":"deepak"},{"age":74,"name":"suresh"},{"age":44,"name":"vinay"}]

更新:不再修改原始数组。

使用xPrototype的sortBy:

var o = [
  { Name: 'Lazslo', LastName: 'Jamf'     },
  { Name: 'Pig',    LastName: 'Bodine'   },
  { Name: 'Pirate', LastName: 'Prentice' },
  { Name: 'Pag',    LastName: 'Bodine'   }
];


// Original
o.each(function (a, b) { console.log(a, b); });
/*
 0 Object {Name: "Lazslo", LastName: "Jamf"}
 1 Object {Name: "Pig", LastName: "Bodine"}
 2 Object {Name: "Pirate", LastName: "Prentice"}
 3 Object {Name: "Pag", LastName: "Bodine"}
*/


// Sort By LastName ASC, Name ASC
o.sortBy('LastName', 'Name').each(function(a, b) { console.log(a, b); });
/*
 0 Object {Name: "Pag", LastName: "Bodine"}
 1 Object {Name: "Pig", LastName: "Bodine"}
 2 Object {Name: "Lazslo", LastName: "Jamf"}
 3 Object {Name: "Pirate", LastName: "Prentice"}
*/


// Sort by LastName ASC and Name ASC
o.sortBy('LastName'.asc, 'Name'.asc).each(function(a, b) { console.log(a, b); });
/*
 0 Object {Name: "Pag", LastName: "Bodine"}
 1 Object {Name: "Pig", LastName: "Bodine"}
 2 Object {Name: "Lazslo", LastName: "Jamf"}
 3 Object {Name: "Pirate", LastName: "Prentice"}
*/


// Sort by LastName DESC and Name DESC
o.sortBy('LastName'.desc, 'Name'.desc).each(function(a, b) { console.log(a, b); });
/*
 0 Object {Name: "Pirate", LastName: "Prentice"}
 1 Object {Name: "Lazslo", LastName: "Jamf"}
 2 Object {Name: "Pig", LastName: "Bodine"}
 3 Object {Name: "Pag", LastName: "Bodine"}
*/


// Sort by LastName DESC and Name ASC
o.sortBy('LastName'.desc, 'Name'.asc).each(function(a, b) { console.log(a, b); });
/*
 0 Object {Name: "Pirate", LastName: "Prentice"}
 1 Object {Name: "Lazslo", LastName: "Jamf"}
 2 Object {Name: "Pag", LastName: "Bodine"}
 3 Object {Name: "Pig", LastName: "Bodine"}
*/

我将给您一个实现选择排序算法的解决方案。它简单有效。

var objs = [
  { first_nom: 'Lazslo', last_nom: 'Jamf'     },
  { first_nom: 'Pig',    last_nom: 'Bodine'   },
  { first_nom: 'Pirate', last_nom: 'Prentice' }
];


function selection_Sort(num) {
  //console.log(num);
  var temp, index;
  for (var i = 0; i <= num.length - 1; i++) {
    index = i;

    for (var j = i + 1; j <= num.length - 1; j++) {
      // You can use first_nom/last_nom, any way you choose to sort

      if (num[j].last_nom < num[index].last_nom) {
        index = j;
      }
    }

    // Below is the swapping part
    temp = num[i].last_nom;
    num[i].last_nom = num[index].last_nom;
    num[index].last_nom = temp;
  };
  console.log(num);
  return num;
}

selection_Sort(objs);
let propName = 'last_nom';

let sorted_obj = objs.sort((a,b) => {
    if(a[propName] > b[propName]) {
        return 1;
    }
    if (a[propName] < b[propName]) {
        return -1;
    }
    return 0;
}

//This works because the js built-in sort function allows us to define our
//own way of sorting, this funny looking function is simply telling `sort` how to
//determine what is larger. 
//We can use `if(a[propName] > b[propName])` because string comparison is already built into JS
//if you try console.log('a' > 'z' ? 'a' : 'z')
//the output will be 'z' as 'a' is not greater than 'z'
//The return values 0,-1,1 are how we tell JS what to sort on. We're sorting on the last_nom property of the object. 
//When sorting a list it comes down to comparing two items and how to determine which one of them is "larger". 
//We need a way to tell JS how to determine which one is larger. 
//The sort defining function will use the case that returns a 1 to mean that a > b
//and the case that returns -1 to mean that a < b