create "contain" function that says if an array contains a certain element and returns true

Asked

Viewed 3,692 times

4

I tried several ways with the indexOf (is a requirement of the issue use), but I’m having a lot of difficulty because I’m learning everything over the internet. The code I’m trying to use does the opposite:

function contem(elemento){
let array =[];
  for(var i=0; i< elemento.length; i++)
   array = elemento.indexOf(i);
      if(array!= -1){
        return true;
      }} 

TIP: Remember that the method indexOf indicates the position of an element in the matrix and also indicates a particular value for elements that are NOT within the matrix.

  • 1

    Use Array.includes() method that returns true or false.

  • 1

    would also use the includes. const list = [1, 2, 3] list.includes(2)return true, for example.

5 answers

7


Checking the existence of a primitive type

If you want to verify the existence of a type primitive, can use the indexOf or includes:

const list = [1, 2, 3, 4, 5];

console.log(list.indexOf(9)); // -1
console.log(list.indexOf(4)); // 3

console.log(list.includes(8)); // false
console.log(list.includes(3)); // true

As you may have noticed above, the two methods are very similar, but:

  • indexOf returns the index of the element you passed as argument. If the element does not exist, -1 will be returned;
  • includes returns a true boolean if the element passed exists in the array. Otherwise, a false boolean will return.

So since it is required the question to use indexOf, we can create a function contain:

const list = [1, 2, 3, 4, 5];

function contain(arr, val) {
  // Vale lembrar que o método `indexOf` retorna o índice do valor
  // caso for encontrado e `-1` caso não for encontrado. Logo, uma das
  // formas de converter o valor para booleano é fazer a comparação
  // conforme abaixo.
  // Se o índice retornado for DIFERENTE de `-1`, `true` será retornado.
  // Caso contrário (o valor não existe, logo, `-1` foi retornado),
  // a comparação abaixo resultará em `false`.
  return arr.indexOf(val) !== -1;
}

console.log(contain(list, 2)); // true
console.log(contain(list, 9)); // false

Therefore, if you want to verify the existence of a primitive type of the array, there is no need to use any repetition loop, such as the for.


Check the existence of an object

However, if you are working with an array of objects, should use a loop loop, such as for. Nevertheless, in this case, the indexOf is not necessary and should not be used.

const list = [
  { id: 1, name: 'Foo' },
  { id: 2, name: 'Bar' },
  { id: 3, name: 'Baz' }
];

function contain(arr, key, val) {
  // Iteramos sobre cada elemento do array:
  for (const obj of arr) {
    // Se existir um objeto com a chave passada (`key`),
    // e for igual ao valor esperado (`val`), retornamos
    // `true`. Caso contrário, passa-se à próxima iteração: 
    if (obj[key] === val) return true;
  }
  
  // Se chegamos até aqui, quer dizer que nenhum objeto da
  // lista satisfaz as nossas condições. Portanto, retornamos `false`.
  return false;
}

console.log(contain(list, 'id', 2)); // true
console.log(contain(list, 'id', 9)); // false

However, instead of creating this huge code to do this, you can make use of the find, that returns the value of the list as long as it satisfies a condition. Note that if no value meets the conditions, undefined will be returned.

Therefore, to the using a negation (NOT) operator twice we were able to convert the return of the method find in a boolean.

See how it gets simpler:

const list = [
  { id: 1, name: 'Foo' },
  { id: 2, name: 'Bar' },
  { id: 3, name: 'Baz' }
]

function contain(arr, key, val) {
  // O método `find` retorna o elemento encontrado. Portanto,
  // utilizamos dois operadores de negação (NOT) para transformar
  // o objeto em um booleano (`true` ou `false`).
  return !!arr.find((obj) => obj[key] === val);
}

console.log(contain(list, 'id', 2)); // true
console.log(contain(list, 'id', 9)); // false

  • I didn’t know how to use . indexof(), but with your explanation it was much clearer. In this case, will the index() always have two parameters in the syntax? Do you know any material that focuses on a more simplified explanation of indexef?

  • Yes, the indexOf takes two arguments: the first of them, which is the element you want to search for the index and the second the starting point of the search. To learn more, read that documentation.

  • I will read, vlw!!

0

//this will check if the number contains in the ELEMENT NAME MATRIX.

function contem(elemento,numero){ 
  var aux = 0;
  for(var i=0; i<10; i++){ 
   if (numero === elemento[i]){
     aux = elemento[i];
  } 
  }
  if (aux > 0 ) {
    return true;
  }
}

0

function contem (array,valor){
 var aux=0;
  for (var i=0 ;i<array.length;i++){
    return (array.indexOf(valor)!=(-1));
  }
}
  • Function contains (array,value){ var aux=0;for (var i=0 ;i<array.length;i++){Return (array.indexof(value)!= (-1));}}

0

 function contem(array,numero){

   let aux = array.indexOf(numero)

   return (aux != -1 == true)


  }

-1

I tested it here it worked.

function contem(vetor, elemento){
    for(var i = 0; i < vetor.length ; i++){
        if(vetor.indexOf(elemento) != -1)
            return true;
    }
    return false
}

Browser other questions tagged

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