Iterate through multiple arrays simultaneously - plz help

Iterate through multiple arrays simultaneously - plz help
0.0 0

#1

I am trying to clean up my html code by not being repetative using jquery. I have 4 videos I want to embed on my portfolio page. I have created 2 arrays, one that stores the video names (vidName) and one that stores the video source (vidSrc). I tried using .each() along with .concat() to iterate through both arrays and .append() them to the html. The videos displayed like I wanted in the DOM, but it also displayed 4 other vid windows underneath that are blank. I am fairly new to code so there is probably an easy solution to get rid of the blank windows, I just can’t wrap my head around it. I also have 6 thumbnails I want to do something similar with, however I will have 3 arrays to work with for those (1 for name, 1 for href, and 1 for image source). I haven’t tried to tackle the thumbnail problem yet, I am hoping the solution to my first problem will help with those.

Here is the code I have used for the videos:

(note: I have the width and height of the iframe set in the real code file, I had to condense to get everything important in the screen shot)

Any help would be greatly appreciated


#2

Could you give us a link to the entire code instead of just this snippet? It really helps to see the total picture and to be able to fork and play around with the code instead of guessing what you may have.


#3

By using concat you have created an array with length 8;

therefore you are looping in that array producing 4 undefined results since vidName[4], vidName[5] ... and src[4], src[5]... does not exists.

The easies solution, assuming that the length of the vidName and the source match (ie for each video there’s a source defined) is a simple for loop that iterates as:

for(var i = 0; i < vidName.length; i++ ) {
 // your append function
}

Out of curiosity, is the two array a mandatory requirement or is your design choice?
If I had control over those data I’d rather have an object as:

var myVideos = {
// vidName: source;
video1: source1;
video2: 'www.youtube.com/blabla'
}

or at the very least an array of array:

[ [name, source], [name, source] ...]

#4

If you want to keep the two separate arrays, you can still use $.each like:

  $.each(vidName, function(i) {
    // your append code
  });

#5

Using 2 arrays was my design choice. It hadn’t occured to me to use a nested array or an object. I guess I still need to train my brain to think differently when dealing with code lol. I used the nested arrays like you suggested with the .each() call and it worked out. Thanks very much for your help!