1

I'm looking for a solution to SEARCH through a jQuery array or object. By this I don't mean checking if the value is contained in the array, I mean searching for related terms as user input. Just the same way we filter ArrayList in Java or even SQL LIKE clause.

For example, let's assume the following is my array

var arr = [ 'Benson', 'Cate', 'John']

If the user types the character e, then Benson and Cate should appear.

Any simplest method to achieve this

2 Answers 2

3

You can use filter like:

var arr = [ 'Benson', 'Cate', 'John' ]
console.log(arr.filter(x => x.includes('e')));

Reference:

Array.prototype.filter()

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

2 Comments

Worked very fine. I only have a very tiny problem. The filter is case sensitive, any way to make it case insensitive?
Yes. arr.filter(x => x.toLowerCase().includes('e'.toLowerCase()))
2

Just adding to @SimoneRossaini's answer.

var arr = [ 'Benson', 'Cate', 'John' ];
const results = document.getElementById('results');
let li;
function search(s) {
    let result = arr.filter(e => e.includes(s));
    results.innerHTML = '';
    result.forEach(name => {
        li = document.createElement('li');
        li.appendChild(document.createTextNode(name));
        results.appendChild(li);
    });
}
<input type="text" id="search" onkeyup="search(this.value)">
<ul id="results"></ul>

Doesn't include JQuery though, maybe it is easy enough to translate this code to JQuery.

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.