Function without every?

Function without every?
0

#1

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;
};

#2

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


#3

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


#4

Should it be arr[i] or what?


#5

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;
};

#6

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.


#7

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


#8

@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);

#9

Did you not advise me against outright giving solutions earlier?


#10

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.


#11

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