Reputation: 66
Can anyone help me with my problem? I tried to use the ARRAY.EVERY method on my array that contains objects. I want the function and the loop to return FALSE and end each time it encounters a convergence between the value entered with the prompt to the NAME variable and the USERNAME values in the individual array objects. In the given example, the function determines false only for the first object in the array when the value of the variable name is the same as username in this object. If the value of the NAME variable coincides, for example, with the second object in the array, the function will show TRUE and it should FALSE. Why is this happening? Shouldn't every method work for every element in an array? It seems the function only considers the first object in the array, and I don't know why. Please help :)! CODEPEN link here - https://codepen.io/gennaro1995/pen/QWNdMdP
const names = [{username: "Mateusz"}, {username: "Kamil"}, {username: "Marcinek"}];
const name = prompt("Your name is here!");
const spr = names.every((num) => {
let result = num.username != name;
console.log(result);
})
Upvotes: 0
Views: 50
Reputation: 166
I assume your goal is to make sure that the user entered value is not already present in the array of name objects.
As already pointed out by Shimon, every()
requires that the passed function returns true/false
, and checks if all the elements in the array satisfy the condition used in the passed function.
Even if one of the element fails to satisfy the condition, every()
returns false
and won't check further.
What you doing is storing the result of the check in a variable and then log it in the console. You are not returning the result of the conditional expression.
Adding one more statement like return result;
as the last statement in the function passed to every()
will make your code work properly.
Upvotes: 0
Reputation: 524
Your problem is that the method in every is not returning a result (true / false). It should look like this in your code:
const spr = names.every((num) => {
let result = num.username != name;
console.log(result);
return result;
});
Every takes a function as a parameter, this function accepts the array element as a parameter, and should return true / false (have a condition). Every asks if all of the array elements return true for the wanted function. If your goal is to return true if the entered name is in the list then you should use some instead, like this:
const names = [
{ username: 'Mateusz' },
{ username: 'Kamil' },
{ username: 'Marcinek' },
];
const name = prompt("Your name is here!");
const spr = names.some((num) => num.username == name);
console.log(spr);
If you want to return true only if the name isn't in names:
const names = [
{ username: 'Mateusz' },
{ username: 'Kamil' },
{ username: 'Marcinek' },
];
const name = prompt("Your name is not here!");
const spr = names.every((num) => num.username != name);
console.log(spr);
Upvotes: 1