按偏移量组数组

时间:2017-10-09 17:22:05

标签: javascript underscore.js

我有以下数组

var player123;

if(jQuery('#player123')){
    bindVideo();
}



function bindVideo(){

    var playerHeight = "500px";
    if(jQuery(window).width() < 1023){
        playerHeight = "100%";
    }else{
        playerHeight = "400px";
    }
    jQuery(window).resize(function(){
        if(jQuery(window).width() < 1023){
            playerHeight = "100%";
        }else{
            playerHeight = "400px";
        }
    });
    player123 = new YT.Player('player123', {
        height: playerHeight,
        width: '100%',
        videoId: 'video-id-here',
        events: {
            'onReady': onPlayerReady(event),
            'onStateChange': onPlayerStateChange
        },
        playerVars:{
            rel:0,
            loop:1,
            showinfo:0,
            controls:0,
            disablekb:1
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    //event.target.playVideo();
}

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
    if(event.data == "2"){
        pauseVideo();
    }else if(event.data == "0"){
        stopVideo();
    }
}

function stopVideo() {
    jQuery("#player-overlay").show();
    player123.stopVideo();
}
function PlayVideo2(){
    jQuery("#player-overlay").hide();
    player123.playVideo();
}
function pauseVideo(){
    jQuery("#player-overlay").show();
    player123.pauseVideo();
}

这些代表两个人对三个不同问题的回答。我希望能够对索引[0,3],[1,4]和[2,5]进行分组。

如果同样的六个回答可能是三个人回答两个不同的问题。在这种情况下,我希望能够通过索引[0,2,4]和[1,3,5]对它们进行分组。

我在这个项目中使用了Underscore,所以一个普通的JS或Underscore解决方案可以解决这个问题!

2 个答案:

答案 0 :(得分:1)

您可以使用Array.from()构建数组,在内部需要来自两次迭代的索引,以便您可以使用i + (n * j)

var arr = ["M", "A", "M", "I", "M", "P"]

function group(arr, n) {
  var part = Math.ceil(arr.length / n);
  return Array.from(Array(n), function(e, i) {
    return Array.from(Array(part), function(a, j) {
      return arr[i + (n * j)]
    })
  })
}

console.log(group(arr, 3))
console.log(group(arr, 2))

答案 1 :(得分:0)

使用Array#filter

&#13;
&#13;
const array = ["M", "A", "M", "I", "M", "P"];

const group = (arr, n) => [...Array(n)].map(
  (_, i) => arr.filter((_, j) => (j - i) % n === 0)
);

console.log(group(array, 2));
console.log(group(array, 3));
&#13;
&#13;
&#13;