Looping through array and output as pairs (divider for each second element)

后端 未结 9 532
旧时难觅i
旧时难觅i 2021-01-18 03:41

I have an array with anonymous elements. Elements are added to the array via php, like so:

$playlist = array();

while (databaseloop) {
  $playlist[] = $a_ti         


        
相关标签:
9条回答
  • 2021-01-18 04:17

    Destructive, but clean:

    while (arr.length) {
      const Title  = arr.shift();
      const Length = arr.shift();
    
      // Do work.
    }
    
    0 讨论(0)
  • 2021-01-18 04:29

    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.

    0 讨论(0)
  • 2021-01-18 04:29
    var arr = ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"];
    
    var group = [];
    for (var x = 0; x < arr.length; x += 2) {
        var track = arr[x],
            length = arr[x + 1];
        group.push({
           track: track,
           length: length
        })
    }
    
    0 讨论(0)
提交回复
热议问题