-1

I am trying to find a string inside an array so there is an input box and i type the value to be searched for. so i created a templated driven form and on submitting it, i stored its value inside variable like

onsubmit(){
 let search=this.searchform.value
console.log(search)
}

So the value that gets displayed in console is

{search: "Bread"}

Now after running the line

  let  titles=this.itemlist.map(i=>i.title);
   console.log(titles)

i have an array which contains the elements as

(2) ["Bread2", "Bread"]

How to search for string inside this array like the varaible "search" that gets consoled after submit the form needs to be search within this array

Ratnabh Kumar Rai
  • 554
  • 2
  • 7
  • 24
  • `array.includes(query)` ... That's a 5 seconds google search. –  Feb 14 '19 at 14:10
  • This question was asked before, check this link: [https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Dom Feb 14 '19 at 14:13

5 Answers5

0

If you want to know if a given string exists in the array and retrieve if its index if it does try this js function:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

Docs can be found here

Kristóf Tóth
  • 791
  • 4
  • 19
0

Try titles.includes(this.searchform.value)

or titles.indexOf(this.searchform.value) > -1

dileepkumar jami
  • 2,185
  • 12
  • 15
0
onsubmit(){
  let search = this.searchform.value
  let titles = this.itemlist.map(i=>i.title);

  let found1 = titles.filter(title => title === search.search)
  let found2 = titles.filter(title => title.includes(search.search))
}

found1 includes title that exactly matched. And found2 includes title that includes search.search as substring.

zmag
  • 7,825
  • 12
  • 32
  • 42
0

You can use includes function of an array for find value is available in the array or not

let result = ["Bread2", "Bread"].includes("Bread");

the result is true if the string is in the array

Another way is to find an index like

let arr = ["Bread2", "Bread"];
let index = arr.indexOf("Bread");

if an index is -1 then this string is not available in array otherwise string is available

console.log(arr[index]); //this will give value of string
Dhaval
  • 868
  • 12
  • 22
-1

filter like this

 let  titles=this.itemlist.map((i)=>
                          {
                            if(i.title===search) return i;
                           });
Ved_Code_it
  • 704
  • 6
  • 10