我有一个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()方法?


当前回答

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

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);

其他回答

还有一个选项:

var someArray = [...];

function generateSortFn(prop, reverse) {
    return function (a, b) {
        if (a[prop] < b[prop]) return reverse ? 1 : -1;
        if (a[prop] > b[prop]) return reverse ? -1 : 1;
        return 0;
    };
}

someArray.sort(generateSortFn('name', true));

默认情况下,它按升序排序。

这是一个简单的问题。我不知道为什么人们会有如此复杂的解决方案。

一个简单的排序函数(基于快速排序算法):

function sortObjectsArray(objectsArray, sortKey)
{
    // Quick Sort:
    var retVal;

    if (1 < objectsArray.length)
    {
        var pivotIndex = Math.floor((objectsArray.length - 1) / 2);  // Middle index
        var pivotItem = objectsArray[pivotIndex];                    // Value in the middle index
        var less = [], more = [];

        objectsArray.splice(pivotIndex, 1);                          // Remove the item in the pivot position
        objectsArray.forEach(function(value, index, array)
        {
            value[sortKey] <= pivotItem[sortKey] ?                   // Compare the 'sortKey' proiperty
                less.push(value) :
                more.push(value) ;
        });

        retVal = sortObjectsArray(less, sortKey).concat([pivotItem], sortObjectsArray(more, sortKey));
    }
    else
    {
        retVal = objectsArray;
    }

    return retVal;
}

使用示例:

var myArr =
        [
            { val: 'x', idx: 3 },
            { val: 'y', idx: 2 },
            { val: 'z', idx: 5 },
        ];

myArr = sortObjectsArray(myArr, 'idx');

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

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

它用于调用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>

对对象数组进行排序

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

// Property to sort by
var args = "last_nom";

// Function to sort the data by the given property
function sortByProperty(property) {
    return function (a, b) {
        var sortStatus = 0,
            aProp = a[property].toLowerCase(),
            bProp = b[property].toLowerCase();
        if (aProp < bProp) {
            sortStatus = -1;
        } else if (aProp > bProp) {
            sortStatus = 1;
        }
        return sortStatus;
    };
}

// Implementation
var sortedArray = booksArray.sort(sortByProperty(args));

console.log("sortedArray: " + JSON.stringify(sortedArray) );

控制台日志输出:

"sortedArray: 
[{"first_nom":"Pig","last_nom":"Bodine"},
{"first_nom":"Lazslo","last_nom":"Jamf"},
{"first_nom":"Pirate","last_nom":"Prentice"}]"

基于此来源改编:代码段:如何按属性对JSON对象数组排序

简单答案:

objs.sort((a,b)=>a.last_nom.localeCompare(b.last_nom))

细节:

今天非常简单,您可以将字符串与localeCompare进行比较。正如Mozilla Doc所说:

localeCompare()方法返回一个数字,指示引用字符串在排序顺序上位于给定字符串之前、之后或与给定字符串相同。

    //example1:
    console.log("aaa".localeCompare("aab")); //-1
    console.log("aaa".localeCompare("aaa")); //0
    console.log("aab".localeCompare("aaa")); //1

    //example2:
    const a = 'réservé'; // with accents, lowercase
    const b = 'RESERVE'; // no accents, uppercase

    console.log(a.localeCompare(b));
    // expected output: 1
    console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
    // expected output: 0

有关详细信息,请参阅Mozilla doclocaleCompare: