Skip to content Skip to sidebar Skip to footer

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:

  1. Filter the list to only get people with that preference - use filter().
  2. Sort the result to order by preference position - use sort().
  3. Convert the results to a comma-separated string of names to show in the alert - use 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);

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?"