Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

184
Views
How to loop through multiple arrays, within an array of arrays using a single value for an index?

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.

7 months ago · Santiago Gelvez
2 answers
Answer question

0

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
    }
});
7 months ago · Santiago Gelvez Report

0

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

7 months ago · Santiago Gelvez Report
Answer question
Find remote jobs