Function without every?

I’m missing something here, most of it is passing, but my initial if statement isn’t checking every value?

Instructions:

Write a function named every that takes an array and a value and returns true if every element of the array equals the value

Example:

If you pass [1,1], 1 it should return true
If you pass [1,2], 1 it should return false
function every(arr, val) {
    
    let emptyarr = true;
    
    for(let i = 0; i < arr.length; i++) {
        if (i !== val){
            return false;
        }
        if (arr.pop() === val){
            return true;
        }
    }
    return emptyarr;
};

Return boots you out of the closest function scope, not out of the nearest loop.

1 Like

are you sure you want to compare i to val in your if?

Should it be arr[i] or what?

Okay, can someone explain why this passed?
I can just check if ALL of the array doesn’t equal val?

function every(arr, val) {
    
    let emptyarr = true;
    
    for(let i = 0; i < arr.length; i++) {
        if (arr !== val){
            emptyarr = false;
        }
        if (arr.pop() === val){
            emptyarr = true;
        }
    }
    return emptyarr;
};

because you set it to false when comparing the entire array every time, then set it true when your popped value matches.

how about looping thru and, if arr[i] doesn’t match, return false. If the entire loop completes, they all must match. return true.

That’s another interesting way. I was close with that way just didn’t do it.

@snowmonkey’s solution would be something like:

const every = (arr, testVal) => {
  for (let val of arr) {
    if (val !== testVal) {
      return false;
    }
  }
  return true;
};

You could also solve it using the filter method available to arrays:

const every = (arr, testVal) => arr.filter(val => val === testVal).length === arr.length;

If it would not be considered “cheating”, you could use the every method available to arrays:

const every = (arr, testVal) => arr.every(val => val === testVal);
1 Like

Did you not advise me against outright giving solutions earlier?

Only FCC challenge solutions. This has nothing to do with Free Code Camp curriculum. Plus, I did not give the solution until the OP solved it first.

1 Like

ah, got it, thank you for clarfying. makes sense.