Array search by name

0

Can you use Arrow Function in this example? If so, what would it look like? What is the best way to do value search?

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");
  }      
 }
    
asked by anonymous 22.01.2018 / 17:57

2 answers

1

It would look 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 includes() method. , but according to the documentation it is still in testing and there may be changes in syntax and behavior.

  

This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal.   Because the spec of this technology has not stabilized, check the compatibility chart for use across multiple browsers. Also note that the syntax and behavior of an experimental technology are subject to changes in the future browser version 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

25.01.2018 / 02:10
0
var msg = ["Orange", "Melancia", "Abobora"];


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

invoking function

buscar("Melancia")
    
22.01.2018 / 18:10