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
Use Array.includes() method that returns true or false.
– Maury Developer
would also use the
includes.const list = [1, 2, 3]list.includes(2)return true, for example.– Carlos Querioz