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

后端 未结 9 534
旧时难觅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: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.

提交回复
热议问题