Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        5个月前关闭。
                                                                                            
                
        
以下是人员ID的数组

var arrPeopleIDs = [1,2,3,4,5];


我想将其从数组末尾分成N个或更少的组。

人:5
除法:单/双(N = 2)


1个单键1
1键可加倍2,3
1键可加倍4,5


// Below output expected
var arrResult = [
 [1], [2,3], [4,5]
];


人:5
除法:单/双/三倍(N = 3)


1键可加倍1,2
1键,三键组合成3、4、5


// Below output expected
var arrResult = [
 [1,2], [3,4,5]
];


人:5
除法:单/双/三/四(N = 4)


1个单键1
1键用于带有2,3,4,5的四边形


// Below output expected
var arrResult = [
 [1], [2,3,4,5]
];


有人可以帮助我提供预期的输出吗?

预先感谢您!

最佳答案

这样分块时将永远只有一个余数,因此您可以安全地对数组进行分块,然后添加余数(如果有):



var arrPeopleIDs = [1, 2, 3, 4, 5, 6];

const chunk = (arr, d) => {
  const temp = arr.slice()
  const out = []
  const rem = temp.length % d

  while (temp.length !== rem) out.unshift(temp.splice(temp.length - d, d))
  rem && out.unshift(temp.splice(0, rem))

  return out
}

console.log(chunk(arrPeopleIDs, 1))
console.log(chunk(arrPeopleIDs, 2))
console.log(chunk(arrPeopleIDs, 3))
console.log(chunk(arrPeopleIDs, 4))
console.log(chunk(arrPeopleIDs, 5))





上面是一个函数,该函数将接收一个数组和一个数字(即块的最大大小),并返回一个分块的数组,从数组末尾开始以最大的块开始,然后从其余部分开始。此函数不会修改原始数组-因此可以多次调用

09-25 17:26
查看更多