Javascript 如何对名称数组进行排序,与名称所在的同一对象中的整数值相关?
这是下面数组的对象Javascript 如何对名称数组进行排序,与名称所在的同一对象中的整数值相关?,javascript,arrays,sorting,Javascript,Arrays,Sorting,这是下面数组的对象 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 = ma
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);
它们的优先顺序可以由数组中列出的插槽所在的索引确定——因此您可以使用该索引来查找,然后您可以像比较一样比较这些索引
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);
});
为此,有3个步骤:
职能员工(姓名、首选项、人员、最大值){
//使用相关字段定义对象employee
this.name=名称;
//按顺序排列的插槽偏好
这个。偏好=偏好;
//所需的强制插槽数
这个人=人;
//可分配的最大插槽数
this.max=max;
}
var staff=新数组();
推送(新员工(“约翰”[1,2,3],1,3]);
推送(新员工(“康拉德”[2,1,4],1,3]);
推送(新员工(“Elliot”[8,2,6,7,1],3,5]);
员工推送(新员工(“Sarah”[3,1,4,2,6],3,5]);
员工推送(新员工(“Emily”[7,2,8,1,4],3,5]);
员工推送(新员工(“标记”,[3,4,1,2],1,3]);
推送(新员工(“Lucy”[5,1,4],1,3]);
推送(新员工(“Sam”[6,2,7],1,3]);
//对搜索的偏好
var-pref=2;
var结果=staff.filter(函数(v){
//如果pref在列表中,则返回true
返回v.preference.indexOf(pref)>-1;
}).排序(功能(a、b){
//比较pre在每个首选项列表中的位置
返回a.preference.indexOf(pref)b.首选项indexOf(pref)?1:0;
}).map(功能(e){
//只需返回此人的姓名
返回e.name;
}).join(“,”);//将名称连接到逗号分隔的列表中
警报(结果)代码>谢谢这帮了大忙: