2012-01-17 39 views
99

Hãy nói rằng bạn có một lớp javascript như thế nàyJavascript - loại đối tượng trong một mảng theo thứ tự abc trên một tài sản của mảng

var DepartmentFactory = function(data) { 
    this.id = data.Id; 
    this.name = data.DepartmentName; 
    this.active = data.Active; 
} 

Hãy nói rằng sau đó bạn tạo ra một số trường hợp của lớp đó và lưu trữ chúng trong một mảng

var objArray = []; 
objArray.push(DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true})); 
objArray.push(DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true})); 
objArray.push(DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true})); 
objArray.push(DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true})); 

Vì vậy, bây giờ tôi sẽ có một loạt các đối tượng được tạo bởi DepartmentFactory. Làm thế nào tôi sẽ đi về bằng cách sử dụng phương pháp array.sort() để sắp xếp mảng này của các đối tượng của các tài sản DepartmentName của từng đối tượng?

Phương pháp array.sort() chỉ hoạt động tốt khi sắp xếp một mảng của chuỗi

var myarray=["Bob", "Bully", "Amy"]; 
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"] 

Nhưng làm thế nào để làm cho nó làm việc với một danh sách các đối tượng?

+0

Bạn có thể chuyển hàm sắp xếp làm đối số đầu tiên cho .sort(). –

+2

Vì bạn đang sử dụng 'DepartmentFactory' làm một hàm tạo, hãy tạo các đối tượng của nó bằng cách sử dụng' new DepartmentFactory', nếu không mảng sẽ được lấp đầy với một loạt các giá trị 'undefined'. – Anurag

Trả lời

169

bạn sẽ phải làm một cái gì đó như thế này:

objArray.sort(function(a, b) { 
    var textA = a.DepartmentName.toUpperCase(); 
    var textB = b.DepartmentName.toUpperCase(); 
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; 
}); 

lưu ý: việc thay đổi trường hợp (để trên hoặc dưới) đảm bảo một trường hợp loại nhạy cảm.

-1

Bạn phải vượt qua một chức năng chấp nhận hai tham số, so sánh chúng, và trả về một số, vì vậy giả sử bạn muốn sắp xếp chúng theo ID bạn sẽ viết ...

objArray.sort(function(a,b) { 
    return a.id-b.id; 
}); 
// objArray is now sorted by Id 
+4

Ông hỏi về sắp xếp theo DepartmentName, không phải Id. –

+0

Tôi đã thử điều này và điều này dường như không hoạt động trên các cột chuỗi ... nó hoạt động trên một cột ngày tháng. Giải pháp làm việc là gì từ @ omer-bokhari – tsando

82

Để hỗ trợ unicode:

objArray.sort(function(a, b) { 
    return a.DepartmentName.localeCompare(b.DepartmentName); 
}); 
+1

Đối với phiên bản không phân biệt chữ hoa chữ thường, hãy sử dụng dòng sau trên dòng 2: 'return a.DepartmentName.toLowerCase(). LocaleCompare (b.DepartmentName.toLowerCase()); ' –

2

DEMO

var DepartmentFactory = function(data) { 
    this.id = data.Id; 
    this.name = data.DepartmentName; 
    this.active = data.Active; 
} 

var objArray = []; 
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true})); 
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true})); 
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true})); 
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true})); 

console.log(objArray.sort(function(a, b) { return a.name > b.name})); 
+0

sẽ làm việc này cho các số nguyên không? –

10
var DepartmentFactory = function(data) { 
    this.id = data.Id; 
    this.name = data.DepartmentName; 
    this.active = data.Active; 
} 

// use `new DepartmentFactory` as given below. `new` is imporatant 

var objArray = []; 
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true})); 
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true})); 
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true})); 
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true})); 

function sortOn(property){ 
    return function(a, b){ 
     if(a[property] < b[property]){ 
      return -1; 
     }else if(a[property] > b[property]){ 
      return 1; 
     }else{ 
      return 0; 
     } 
    } 
} 

//objArray.sort(sortOn("id")); // because `this.id = data.Id;` 
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;` 
console.log(objArray); 

demo: http://jsfiddle.net/diode/hdgeH/

0

làm điều đó như thế này

objArrayy.sort(function(a, b){ 
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase() 
if (nameA < nameB) //sort string ascending 
    return -1 
if (nameA > nameB) 
    return 1 
return 0 //default return value (no sorting) 
}); 
console.log(objArray) 
4
// Sorts an array of objects "in place". (Meaning that the original array will be modified and nothing gets returned.) 
function sortOn (arr, prop) { 
    arr.sort (
     function (a, b) { 
      if (a[prop] < b[prop]){ 
       return -1; 
      } else if (a[prop] > b[prop]){ 
       return 1; 
      } else { 
       return 0; 
      } 
     } 
    ); 
} 

//Usage example: 

var cars = [ 
     {make:"AMC",  model:"Pacer", year:1978}, 
     {make:"Koenigsegg", model:"CCGT", year:2011}, 
     {make:"Pagani",  model:"Zonda", year:2006}, 
     ]; 

// ------- make ------- 
sortOn(cars, "make"); 
console.log(cars); 

/* OUTPUT: 
AMC   : Pacer : 1978 
Koenigsegg : CCGT : 2011 
Pagani  : Zonda : 2006 
*/ 



// ------- model ------- 
sortOn(cars, "model"); 
console.log(cars); 

/* OUTPUT: 
Koenigsegg : CCGT : 2011 
AMC   : Pacer : 1978 
Pagani  : Zonda : 2006 
*/ 



// ------- year ------- 
sortOn(cars, "year"); 
console.log(cars); 

/* OUTPUT: 
AMC   : Pacer : 1978 
Pagani  : Zonda : 2006 
Koenigsegg : CCGT : 2011 
*/ 
-4

Một câu trả lời đơn giản:

objArray.sort(function(obj1, obj2) { 
    return obj1.DepartmentName > obj2.DepartmentName; 
}); 

ES6 cách:

objArray.sort((obj1, obj2) => {return obj1.DepartmentName > obj2.DepartmentName}; 

Nếu bạn cần phải làm cho nó chữ thường/hoa vv, chỉ cần làm điều đó và lưu trữ mà kết quả trong một biến hơn so sánh biến đó. Ví dụ:

objArray.sort((obj1, obj2) => { 
    var firstObj = obj1.toLowerCase(); 
    var secondObj = obj2.toLowerCase(); 
    return firstObj.DepartmentName > secondObj.DepartmentName; 
}); 
Các vấn đề liên quan