1

The below autocomplete function returns all users from associative $filteredUsersArray instead of what I type in html input tag. I only need to get the user I'm looking for. The function(request) is being executed correctly depending on what I type into input. The code works for standard, non-associative array. I'm passing associative array with user id's to then use the id for POSTing private message.

autocomplete function:

$userSearchbox.autocomplete({
    source: function(request, response) {

        response($.map($filteredUsersArray, function (value, key) {
            return {
                label: value.username,
                value: key.id
            }
        }));
    }
});

$filteredUsersArray:

    [{
    "id": "1",
    "userName": "maciek"
}, {
    "id": "2",
    "userName": "stefan"
}, {
    "id": "3",
    "userName": "newuser"
}, {
    "id": "8",
    "userName": "papaitalia"
}, {
    "id": "9",
    "userName": "nowy_user"
}, {
    "id": "12",
    "userName": "zenek"
}]

autocomplete result on the page: enter image description here

1
  • Javascript doesn't have associative arrays, only indexed arrays. Commented Oct 20, 2018 at 18:52

1 Answer 1

2

Your use of the $.map function is not the best approach for this problem. That is because the concept of a map is to map old items to new items in a 1-to-1 method. If you're starting array has 25 items, and you map over it, you get a new array that is also 25 items.

What you want to do is FILTER your data!

In vanilla Javascript land, there is a convenient .filter() function you may call on any array. But in jQuery land, the function is called $.grep(array, function); The first argument is the original array you want to filter. The second argument is a function, and it is very important.

The function you pass into your $.grep call is a test, and it will be called one time for every item in the original array. If the test returns true, the item being tested is added to the new array. If the test returns false, the item is not added to the new array. The result of the whole $.grep function is a new array containing only items that passed the test. A Filtered Array!!! :D

You did not include enough code for me to create a perfect copy+paste solution, but here is a very small and simple demo. Examine it carefully, and do your best to apply these concepts to your own code. Good luck!!

JS Fiddle (with comments & console logs)

JS Fiddle (no comments)

Read about $.grep() at jQuery Docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.