Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

javascript - 使用Lodash将JavaScript数组拆分为多个块(Split JavaScript array in chunks using Lodash)

I need to split a JavaScript array into n sized chunks.(我需要将一个JavaScript数组拆分为n大小的块。)

Eg: Given this array(例如:鉴于此数组)

["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]

and a n equals to 4, the output should be this:(并且n等于4,输出应为:)

[ ["a1", "a2", "a3", "a4"],
  ["a5", "a6", "a7", "a8"],
  ["a9", "a10", "a11", "a12"],
  ["a13"]
]

I aware of pure JavaScript solutions for this problem, but since I am already using Lodash I am wondering if Lodash provides a better solution for this.(我知道可以解决此问题的纯JavaScript 解决方案 ,但是由于我已经在使用Lodash,所以我想知道Lodash是否可以为此提供更好的解决方案。)

Edit:(编辑:)

I created a jsPerf test to check how much slower the underscore solution is.(我创建了一个jsPerf测试来检查下划线解决方案的速度。)

  ask by Cesar Canassa translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at lodash' chunk : https://lodash.com/docs#chunk(看看lodash的https ://lodash.com/docs#chunk)

 const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; const chunks = _.chunk(data, 3); console.log(chunks); // [ // ["a1", "a2", "a3"], // ["a4", "a5", "a6"], // ["a7", "a8", "a9"], // ["a10", "a11", "a12"], // ["a13"] // ] 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...