Search code examples
javascriptarrays

How to exclude an array of indexes from loop


I have an array y like this:

var y = [1, 2, 3, 4];

And I would like to iterate through the array, but exclude some indexes. The indexes are saved in second array

var x = [1,3];

So, I want to write each numbers from an array y, but not the numbers on the position 1,3, which come from array x

I tried to skip the numbers on these positions, but with no success. Could you please help me? Here is what I tried

for (var i = 0; i < y.length; i++) {
    for (var j = 0; j < x.length; j++) {
            if (i === x[j]) {
        continue;
     } 
    }
 console.log(y[i]);
}

Solution

  • You could use the Array.includes() method.

    var list = [1,2,3,4];
    var skipIndexes = [1,3]; 
    
    for (var i = 0; i< list.length; i++) {
     if (! skipIndexes.includes(i)) {
      console.log(list[i]); 
     }
    }