Skip to content Skip to sidebar Skip to footer

Looping Through Array And Output As Pairs (divider For Each Second Element)

I have an array with anonymous elements. Elements are added to the array via php, like so: $playlist = array(); while (databaseloop) { $playlist[] = $a_title; $playlist[] = $a

Solution 1:

Well, maybe this is the most basic solution:

for (var i = 0; i < arr.length; i += 2) {
    var title = arr[i];
    varlen = arr[i+1];
}

However, I would recommend you to arrange $playlist as follows:

while (databaseloop) {
    $playlist[] = array(
        "title" => $a_title,
        "length" => $a_length
    );
}

Then it will be easy to iterate the elements simply with:

for (var i = 0; i < arr.length; i++) {
    var title = arr[i]['title'];
    varlen = arr[i]['length'];
}

Solution 2:

You could split the array into an array of two-element arrays.

var arr = ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"];
arr.map(function(elem,i,arr){return [elem, (i+1<arr.length) ? arr[i+1] : null];})
    .filter(function(elem,i){return !(i%2);});

Solution 3:

Using Array.prototype.reduce():

let pairs = playlist.reduce((list, _, index, source) => {
    if (index % 2 === 0) {
        list.push(source.slice(index, index + 2));
    }
    return list;
}, []);

This gives you a 2-dimensional array pairs to work with.

Solution 4:

Not with foreach.

for (var i = 0; i < array.length; i += 2) {
    var name = array[i];
    var time = array[i + 1];
    // do whatever
}

Solution 5:

A simple for loop with an increment of two. You might want to make sure that your array length is long enough for i+1, in case the length isn't divisible by 2!

for (i = 0; i+1 < array.length; i+=2) {
  name = array[i];
  length = array[i+1];
}

Post a Comment for "Looping Through Array And Output As Pairs (divider For Each Second Element)"