How To Sort An Array Of Names, Relevant To The Value Of An Integer In The Same Object As The Name?
This is the object for the array below. function Employee (name,preference,man,max){ // Defines the object employee with the relevant fields this.name = name; // slot prefere
Solution 1:
There are 3 steps to this:
- Filter the list to only get people with that preference - use
filter()
. - Sort the result to order by preference position - use
sort()
. - Convert the results to a comma-separated string of names to show in the alert - use
map()
.
functionEmployee(name, preference, man, max) {
// Defines the object employee with the relevant fieldsthis.name = name;
// slot preference in orderthis.preference = preference;
// Number of mandatory slots requiredthis.man = man;
// Maximum number of slots that can be allocatedthis.max = max;
}
var staff = newArray();
staff.push(newEmployee("john", [1, 2, 3], 1, 3));
staff.push(newEmployee("Conrad", [2, 1, 4], 1, 3));
staff.push(newEmployee("Elliot", [8, 2, 6, 7, 1], 3, 5));
staff.push(newEmployee("Sarah", [3, 1, 4, 2, 6], 3, 5));
staff.push(newEmployee("Emily", [7, 2, 8, 1, 4], 3, 5));
staff.push(newEmployee("Mark", [3, 4, 1, 2], 1, 3));
staff.push(newEmployee("Lucy", [5, 1, 4], 1, 3));
staff.push(newEmployee("Sam", [6, 2, 7], 1, 3));
// the preference to search onvar pref = 2;
var results = staff.filter(function (v) {
// return true if pref is in the listreturn v.preference.indexOf(pref) > -1;
}).sort(function (a, b) {
// compare position of pre in each preference listreturn 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 personreturn e.name;
}).join(', '); // join names into comma-separated listalert(results);
Solution 2:
Their preference ordering can be determined by the index at which that slot is listed in the array - so you'd used indexOf
to find that, and then you can compare those indices just as you would compare any other properties.
indexOf
would return -1
if the item does not occur in the array, which would make the highest preference actually. However, as we filter those out that don't have them in their preference field we don't need to care about that.
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);
});
Post a Comment for "How To Sort An Array Of Names, Relevant To The Value Of An Integer In The Same Object As The Name?"