2017-07-06 51 views
-2

我有以下几点:如何排序下面的对象和字符串数组?

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

什么是对列表进行排序,以便字符串是在前面的最佳途径,和对象跟从?

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

检查你的值的类型r排序处理程序。 –

+6

[so]是*不*免费代码写作服务。预计你会尝试**自己编写代码**。在[做更多研究]之后(http://meta.stackoverflow.com/questions/261592),如果你有问题,你可以**发布你已经尝试过**的清单,说明什么是不工作的**并提供** [mcve] **。 – Igor

+0

,可以用[了'typeof'操作](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof),以确定在数组中的元素的类型。请注意,如果元素为null,这将返回'object'。 – glhrmv

回答

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
// 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使xy更高的优先级,否则+1返回之前把yx

+0

顺便说一句,你可以删除的typeof的支架以及 – dejakob

+1

@dejakob我不知道这是可能的。谢谢! – OverCoder

+0

我喜欢简洁。一个班轮看起来非常漂亮。 – Rolando

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

相关问题