reza laki
reza laki

Reputation: 101

javascript/jquery simple search engine - implement a simple search engine, data stored in an array

Question is Edited! I have stored all products name in an Array in object format. I have a input[type=text], too. I need a simple code to search among this array. SQL command is like : (SELECT name FROM tbl_product WHERE name LIKE %txt% ). But I am implementing this on frond-end and there is no connection to back-end!

<input type="text" id="mytxt" />

<script>
// [{ in_ordered_id : "product name"}, ...]
var products_name = [{ 8 : "product ninety two"}, {21 : "product two"}, {35 : "product nine"} , ....];
$("#mytxt").keyup(function(){
     var txt = $("#mytxt").val();
     var results = start_search(txt); // `results` must be array of ids e.g. [35, 98]

});

function start_search(text){
     /// I don't know what to write here
}
</script>

Upvotes: 0

Views: 856

Answers (2)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11305

string.includes might help

products_name = ["product one", "product two"];


$("#mytxt").keyup(function() {
  var txt = $("#mytxt").val();
  var results = start_search(txt);
  console.log(results);
});

function start_search(text) {
  return products_name.filter(pr => pr.includes(text))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="mytxt">

--Edit

const products_name = [{
  8: "product ninety two"
}, {
  21: "product two"
}, {
  35: "product nine"
}]


$("#mytxt").keyup(function() {
  var txt = $("#mytxt").val();
  var results = start_search(txt);
  console.log(results);
});

function start_search(text) {
  return products_name.filter(pr => Object.values(pr)[0].includes(text)).map(pr => Number(Object.keys(pr)[0]))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="mytxt">

Upvotes: 1

Schabbi
Schabbi

Reputation: 141

How about using the array.indexOf function?

products_name = ["product one", "product two"];

function start_search(text){
     if(products_name.indexOf(text) > -1){
        return true;
    }else{
        return false;
    }
};

start_search('product'); // returns false
start_search('product one'); // returns true
start_search('product two'); // returns true
start_search('product three'); // returns false

Upvotes: 0

Related Questions