2014-11-25 1 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

Спасибо это помогло: –

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); 
}); 
Смежные вопросы