Question

I want to categorize jQuery autocomplete results as in the documentation, but I also want to limit the number of results in each category. I understand how to limit the number of total results using an if statement or slice, but I cannot figure out how to use them in combination with the categories functionality.

Say my data looks like this:

var data = [
  { label: "Location #1", category: "city" },
  { label: "Location #2", category: "city" },
  { label: "Location #3", category: "city" },
        // ...more locations \\
  { label: "Location #25", category: "city" },
  { label: "Person #1", category: "people" },
  { label: "Person #2", category: "people" },
  { label: "Person #3", category: "people" },
        // ...more people  \\
  { label: "Person #25", category: "people" }
];

If I limit the number of results to 5 using one of the above methods, this affects the total number of results, so if a user starts typing "o" in the search field, they will see:

CITIES: Location #1, Location #2, Location #3, Location #4, Location #5

What I want to display, however, is a limit of 5 locations and 5 people:

CITIES: Location #1...Location #5

...followed by:

PEOPLE: Person #1...Person #5

My actual data is coming from a more complicated SQL query in CartoDB, but here is a simple JSFiddle that should suffice: http://jsfiddle.net/vqwBP/577/

Was it helpful?

Solution

The Javascript Array.Filter method can do what you need. The predicate function fn must track a counter for each category, so it is wrapped inside a closure that maintains this state information. The counter object must be extended to reflect all the possible categories exactly (case-sensitive).

var predicate = function () {
    var counter = { city: 0, people: 0, elves: 0 };
    var fn = function(item) {
        counter[item.category] += 1;
        return (counter[item.category] <= 5);
    }
    return fn;
}();

response(results.filter(predicate));

Try it at http://jsfiddle.net/Cfp2N/3/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top