2014-11-25 65 views
2

這是以下數組的對象。如何對與名稱相同的對象中的整數值相關的名稱數組進行排序?

function Employee (name,preference,man,max){ 
    // Defines the object employee with the relevant fields 
    this.name = name; 
    // slot preference in order 
    this.preference = preference; 
    // Number of mandatory slots required 
    this.man = man; 
    // Maximum number of slots that can be allocated 
    this.max = max; 
}  

這是下面的數組。第二個字段值(表示時間表中的插槽)已按優先順序排序。我希望能夠選擇一個特定的插槽並提醒一個列表,其中包含所有在其偏好字段中擁有該列表的人以及按照最高優先級列出的人的順序。

var staff = new Array(); 
staff.push(new Employee("john",[1,2,3],1,3)); 
staff.push(new Employee("Conrad",[2,1,4],1,3)); 
staff.push(new Employee("Elliot",[8,2,6,7,1],3,5)); 
staff.push(new Employee("Sarah",[3,1,4,2,6],3,5)); 
staff.push(new Employee("Emily",[7,2,8,1,4],3,5)); 
staff.push(new Employee("Mark",[3,4,1,2],1,3)); 
staff.push(new Employee("Lucy",[5,1,4],1,3)); 
staff.push(new Employee("Sam",[6,2,7],1,3)); 
showEmployees(staff); 

回答

1

有3個步驟是:

  1. 過濾列表,只讓人們與偏好 - 使用filter()
  2. 對結果進行排序以按優先順序排序 - 使用sort()
  3. 將結果轉換爲逗號分隔的字符串以顯示在警報中 - 使用map()

function Employee(name, preference, man, max) { 
 
    // Defines the object employee with the relevant fields 
 
    this.name = name; 
 
    // slot preference in order 
 
    this.preference = preference; 
 
    // Number of mandatory slots required 
 
    this.man = man; 
 
    // Maximum number of slots that can be allocated 
 
    this.max = max; 
 

 
} 
 

 
var staff = new Array(); 
 
staff.push(new Employee("john", [1, 2, 3], 1, 3)); 
 
staff.push(new Employee("Conrad", [2, 1, 4], 1, 3)); 
 
staff.push(new Employee("Elliot", [8, 2, 6, 7, 1], 3, 5)); 
 
staff.push(new Employee("Sarah", [3, 1, 4, 2, 6], 3, 5)); 
 
staff.push(new Employee("Emily", [7, 2, 8, 1, 4], 3, 5)); 
 
staff.push(new Employee("Mark", [3, 4, 1, 2], 1, 3)); 
 
staff.push(new Employee("Lucy", [5, 1, 4], 1, 3)); 
 
staff.push(new Employee("Sam", [6, 2, 7], 1, 3)); 
 

 
// the preference to search on 
 
var pref = 2; 
 

 
var results = staff.filter(function (v) { 
 
    // return true if pref is in the list 
 
    return v.preference.indexOf(pref) > -1; 
 
}).sort(function (a, b) { 
 
    // compare position of pre in each preference list 
 
    return a.preference.indexOf(pref) < b.preference.indexOf(pref) ? -1 
 
     : a.preference.indexOf(pref) > b.preference.indexOf(pref) ? 1 : 0; 
 
}).map(function (e) { 
 
    // just return the name of the person 
 
    return e.name; 
 
}).join(', '); // join names into comma-separated list 
 

 
alert(results);

+0

謝謝這已經幫助了很多: – 2014-11-26 09:41:54

0

自己的喜好排序產生着該插槽數組中列出的索引來確定 - 所以你最好使用indexOf發現,然後你可以比較的指標,就像你compare any other properties

indexOf將返回-1如果項目不在數組中,這將實際上使最高優先。但是,當我們篩選那些在他們的偏好領域沒有的人時,我們不需要關心這些。

var slot = …; 
staff.filter(function(employee) { 
    return employee.preference.indexOf(slot) > -1; 
}).sort(function(a, b) { 
    return a.preference.indexOf(slot) - b.preference.indexOf(slot); 
}); 
相關問題