create "contains" function that tells if an array contains a certain element and returns true
I have tried several ways with indexOf
(it is a requirement of the question to use), but I am having a lot of difficulty, because I am 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 array and also indicates a particular value for elements that are not inside the array.
5 answers
Check the existence of a primitive type
If you want to verify the existence of a primitive type , you 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 quite similar, but:
-
indexOf
returns the index of the element you passed as an argument. If the element does not exist,-1
will be returned; -
includes
returns a boolean true if the passed element exists in the array. Otherwise, a false boolean will return.
Then, since it is a requirement of 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 check for the existence of a primitive type of the array, there is no need to use any repeat loops, such as for
.
Check the existence of an object
However, if you are working with an array of objects , you should use a repeat loop, such as for
. Despite this, in this case 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 find
, which returns the value of the list as long as it satisfies a condition. Note that if no value satisfies the conditions, undefined
will be returned.
Therefore, to using a negation operator (NOT) twice we can convert the return of the method find
into a boolean.
Here's 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
/ / this will check if the number contains in the element name array.
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;
}
}
function contem (array,valor){
var aux=0;
for (var i=0 ;i<array.length;i++){
return (array.indexOf(valor)!=(-1));
}
}
function contem(array,numero){
let aux = array.indexOf(numero)
return (aux != -1 == true)
}
I tested here worked out.
function contem(vetor, elemento){
for(var i = 0; i < vetor.length ; i++){
if(vetor.indexOf(elemento) != -1)
return true;
}
return false
}