如何对以下对象和字符串数组进行排序?

时间:2017-07-06 17:26:05

标签: javascript ecmascript-6

我有以下内容:

myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]

对列表进行排序的最佳方法是什么,以便字符串在前面,对象在后面?

["Abigail", "Kelsey", {'name':'Adam'}, {'name': 'Jennifer'}, {'name': 'Jorden'}]

3 个答案:

答案 0 :(得分:3)

var myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}];

myitems.sort(function(a, b) {
  if(typeof a === "string") {                                       // if a is a string
     if(typeof b === "string") return a.localeCompare(b);           // and b is a string, then compare the 2 strings a and b
     return -1;                                                     // otherwise (a is a string and b is an object) then make a go above b
  }
  else {                                                            // if a is an object
     if(typeof b === "object") return a.name.localeCompare(b.name); // and b is an object, then compare the 2 objects' names a.name and b.name
     return 1;                                                      // otherwise (a is an object and b is a string) then make a go bellow b
  }
});

console.log(myitems);

答案 1 :(得分:1)

// Assign to a variable
myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]
// Sort them
myitems = myitems.sort((x, y) => typeof(x) === 'string' ? -1 : 1)

详细了解sort方法,了解其工作原理。

基本上,排序函数需要两个参数xy来排序。如果x的类型为字符串,则会返回-1,以便x的优先级高于y,否则会返回+1以放置yx之前

答案 2 :(得分:1)

var myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]

var result = myitems.sort(function(a,b) {
  if(typeof a === 'string' && typeof b === 'object')
    return -1;
  else if(typeof a === 'object' && typeof b === 'string')
    return 1;
  else if(typeof a === 'string' && typeof b === 'string')
    return a.localeCompare(b);
  else
    return a.name.localeCompare(b.name);
    
});
console.log(result);