简体   繁体   中英

Array elements into sub-arrays?

My question is the following: How to group array elements into sub-arrays inside the same array with javascript?

Example : [ 11, 5, 13, 10, 23, 25, 7, 6 ]

The result I want to achieve: [ [11, 5], [13, 10], [23, 25], [7, 6] ]

Since we're getting answers now, at least let's simplify the method:

 var arr = [ 11, 5, 13, 10, 23, 25, 7, 6 ]; let newArr = arr.reduce((acc, n, i) => { i = Math.floor(i/2); // Calculate the proper index acc[i] = acc[i] || []; // Make sure acc[i] is an array acc[i].push(n); // Add the current value to the array. return acc; }, []); console.log(newArr);

You can just iterate through the array and find the index by using index/2 . Then create an array or push the index element into the array. Below is the full code.

 var arr = [ 11, 5, 13, 10, 23, 25, 7, 6 ]; let newArr = arr.reduce((acc, curr, i) => { let index = Math.floor(i/2); let a = acc[index] || []; a.push(curr); acc[index] = a; return acc; }, []); console.log(newArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM