How to find a vector using a JAVASCRIPT function

Asked

Viewed 171 times

2

I want to return true or false if you locate Reactjs in the vector, but always returns false, I did not want to have the answer face, but an explanation of why this giving wrong grateful since already.

var skills = [ "JavaScript", "ReactJS", "React Native"];

          function temhabilidade(skills){

        var resultado = skills.indexOf('ReactJS'); 
        if(resultado == 'ReactJS'){
          return true;
        }else{
          return false;
        }          
      }     
      var mostra = temhabilidade('ReactJS');
      console.log(mostra);

4 answers

5

The method index() returns the first index where the element can be found in the array and returns -1 if the element is not found.

In your case it would be better to use the method includes()

function temhabilidade(skills){
    if (skills.includes('ReactJS'))
        return true;

    return false;   
} 
  • 4

    Instead of the if, may simply be: return skills.includes('ReactJS')

2

You are giving false because the index does not return a boolean, and also will not return the value 'Reactjs', so, result will never be equal to 'Reactjs'.

The index() method returns the first index where the element can be found in the array, returns -1 if it is not present.

The cool thing would be in this function you create a filter with your own filter

const skils = ['NodeJS', 'ReactJS', 'PHP']
skils.filter(function(skill){
  if(skill === 'ReactJS') {
    return console.log(true)
  }
})

Obviously, this way I gave example I think it does not fit in any application, but it is only to exemplify.

2

A very good method to use is also the some(), with it through a callback function is returned the boolean value true if at least one of the elements in the array matches the condition.

const skils = ['NodeJS', 'ReactJS', 'PHP']

function temhabilidade(skills) {
  return skils.some(skill => skill == skills)
}

let mostra = temhabilidade('ReactJS');
console.log(mostra);

The pq of your code is always returning false, already explained by colleagues.

0

In this case you are renaming the array variable

var skills = [ "JavaScript", "ReactJS", "React Native"];

function temhabilidade(search){
  var resultado = skills.indexOf(search); 
  return resultado > 0 ? true : false;
}     

var mostra = temhabilidade('ReactJS');
console.log('achou ReactJS? '+ mostra);

var mostra = temhabilidade('ABC');
console.log('achou ABC? '+ mostra);

Browser other questions tagged

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