Array search by name

Asked

Viewed 107 times

-1

Can I use Arrow Function in this example? If so, how would I look? What is the best way to search for value?

var msg =  ["Orange", "Melancia", "Abobora"];
 
var fruta = "Melancia"
  
buscar(fruta);

 function buscar(str){
  if(msg.indexOf(str) > -1){
    console.log(str);
  }else{
    console.log("Fruta não encontrada");
  }      
 }

  • 3

    I couldn’t figure out what you want. Do you search the list by the index where the word "watermelon" is for "watermelon" at the end? It didn’t make sense to me.

  • @Andersoncarloswoss I’m going to make sense of logic

2 answers

1


She’d be like this:

var lista =  ["Orange", "Melancia", "Abobora"];
const buscar = str => (lista.indexOf(str) > -1) ? console.log('Encontrada') : console.log("Não encontrada");
buscar("Melancia");
buscar("Não existe");

You can also use the method includes(), but according to the documentation it is still in tests and can occur changes in syntax and behavior.

This is an experimental technology, part of the Ecmascript 2016 (ES7) proposal. As the specification of this technology has not stabilized, check the compatibility table for use in multiple browsers. Also note that the syntax and behavior of an experimental technology are subject to changes in the future version of the browsers as the specification changes. - Free translation.

var lista =  ["Orange", "Melancia", "Abobora"];
const buscar = str => (lista.includes(str)) ? console.log('Encontrada') : console.log("Não encontrada");
buscar("Melancia");
buscar("Não existe");

References

0

var msg = ["Orange", "Melancia", "Abobora"];


var buscar = nome => msg.filter((elemento) => elemento.toLowerCase() === nome.toLowerCase())

calling function

buscar("Melancia")
  • 1

    filter returns a new array soon would have to make a condition to know if obtained return.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.