-4

Okay, I have seen this: Sort array of objects by string property value in JavaScript
Now, my problem is that I want sort the array by a field value in dependence of an external int value.

The Int value represents a number of persons for a reservation, the objects in the array are the tables with the seats.

Now, when I got a Reservation with 4 persons the array should beginn with the object where Seats are equal to my Int (the 4 persons) or the nearest higher one. The next ones should be i.e. 6 and 8. Objects with Seats are smaller then my Int should listed at the end (when 4 persons want a reservation, I dont need tables with 2 Seats). I hop its a bit cleare now.

{
    Area: "Bar",
    Seats: 2,
    Id : 1
},{
    Area: "Outside",
    Seats: 8,
    Id : 2
},{
    Area: "Room",
    Seats: 4,
    Id : 3
},{
    Area: "Floor",
    Seats: 2,
    Id : 4
},{
    Area: "Room",
    Seats: 6,
    Id : 5
}

Okay, here is my solution:

        res.sort(function (a, b) {
            if ((a.Seats < goal)  &&  (b.Seats < goal)) {
                return b.Seats - a.Seats;
            }
            if (a.Seats < goal) {
                return 1;
            }
            if (b.Seats < goal) {
                return -1;
            }
            return a.Seats - b.Seats;
        });
Community
  • 1
  • 1
chris
  • 4,827
  • 6
  • 35
  • 53
  • @Juhana How does that answer deal with the special case of the field value matching the int variable? – Barmar Jun 13 '14 at 07:51
  • You should fix your spelling mistakes and show what you have already tried. It's hard to understand what you're aiming to do. – kemicofa ghost Jun 13 '14 at 07:51
  • I don't understand the ordering of the items that don't match the goal. It looks random. – Barmar Jun 13 '14 at 07:55
  • 1
    @Barmar It's reasonably close enough to solve the problem. If the OP doesn't manage it completely, it should get them partway through and they can show the effort they've made. – JJJ Jun 13 '14 at 07:57

1 Answers1

3
var goal = 4;
array.sort(function(a, b) {
    if (a.Seats == goal) {
        return -1;
    } else if (b.Seats == goal) {
        return 1;
    } else { // If neither matches the goal, order them by Seats
        return a.Seats - b.Seats;
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612