1

I'm looping through an object using for loop, and I would like to ignore some specific values when looping.

This block of code is responsible to loop through my object:

let acceptAll = function (rawContent){
   for(let i in rawContent)
   if(!rawContent[i]) return false;
   return true
};

I have a value in rawContent that I would like to ignore when looping through, is that possible?

Many thanks in advance!

  • You haven't said what `rawContent` is, but if it's an array, `for-in` isn't usually the right choice for looping through it. I do a rundown of your options in [this answer](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476), but for most use cases you'd use `for-of` in modern environments. – T.J. Crowder Feb 10 '21 at 08:24

3 Answers3

2

You have a couple of options:

  1. if continue

  2. if on its own

Here's if continue:

for (let i in rawContent) {
    if (/*...you want to ignore it...*/) {
        continue; // Skips the rest of the loop body
    }
    // ...do something with it
}

Or if on its own:

for (let i in rawContent) {
    if (/*...you DON'T want to ignore it...*/) {
        // ...do something with it
    }
}

Side note: That's a for-in loop, not a for loop (even though it starts with for). JavaScript has three separate looping constructs that start with for:

  • Traditional for loop:

    for (let i = 0; i < 10; ++i) {
          // ...
    }
    
  • for-in loop:

    for (let propertyName in someObject) {
          // ...
    }
    

    (If you never change the value in propertyName in the loop body, you can use const instead of let.)

  • for-of loop:

    for (let element of someIterableLikeAnArray) {
          // ...
    }
    

    (If you never change the value in element in the loop body, you can use const instead of let.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

I guess you are searching for the continue keyword:

let array = [1,2,3,4]

for(let i of array){
    if(i === 2) continue
  console.log(i)
}
Imit
  • 68
  • 6
0

You can maintain an array of values which you would like to ignore. For example

const valuesToIgnore = [1,5,15,20]
let acceptSome = (rawContent) => {
    for (let i of rawContent) {
        if (valuesToIgnore.includes(i)) {
        // These are the values you want to ignore
            console.log('Ignoring', i)
        } else {
        // These are the values you do not want to ignore
            console.log('Not Ignoring', i)
        }
    }
}

// And you invoke your function like this -

acceptSome([1,2,3,5,10,15,20,25])
Pawan Sharma
  • 1,842
  • 1
  • 14
  • 18