Home > Back-end >  How to loop through multiple arrays, within an array of arrays using a single value for an index?
How to loop through multiple arrays, within an array of arrays using a single value for an index?

Time:06-14

I'm trying to solve a problem where you have an array

array = [[a,b,c],[e,f,g],[h,i,j]]

I want to loop through the first letter of the first array, then look at the first of all the other arrays then do a comparison whether they're equal or not. I'm unsure how to do this given that a loop will go through everything in its array. I wrote a nested loop below, but I know it's know it's not the right approach. I basically want something that looks like if (array[0][0] == array[1][0] == array[2][0]), then repeat for each element in array[0]

  var firstWord = array[0];
  var remainderWords = array.slice(1); 
  for(var i = 0; i < firstWord.length; i  ){
    for (var j = 0; i< remainderWords.length; j  ){

      if firstWord[i] == remaindersWord[j][i]
    }

Any help would be appreciated.

CodePudding user response:

Use Array.every() to check that a condition is true for all elements of an array.

firstWord.forEach((letter, i) => {
    if (remainderWords.every(word => word[i] == letter)) {
        // do something
    }
});

CodePudding user response:

You can use three nested for or .forEach loops to get to the items in the remainderItems array. Try this

var array = [['a', 'b', 'c'], ['b', 'f', 'g'], ['h', 'c', 'j']];
var firstWord = array[0];
var remainderWords = array.slice(1);

firstWord.forEach((l, idx) => {
  remainderWords.forEach(arr => {
    arr.forEach(v => {
      if (l == v) {
        // matched do whatever you want with the variable here
        console.log(v)
      }
    })
  })
})

  • Related