0
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue)
  },
  []
)
// flattened is [0, 1, 2, 3, 4, 5]

How do I reverse this?

I have this array [0, 1, 2, 3, 4, 5] and I want to convert to this one [ [0, 1], [2, 3], [4, 5] ];

Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
Ossy
  • 73
  • 1
  • 5
  • 3
    Just a tip, for flattening an array you could also just do `array.flat()` – Reyno Jun 09 '20 at 09:50
  • Though it's worth noting that `array.flat()` [won't work in Internet Explorer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Browser_compatibility). – Tim Jun 09 '20 at 14:57

4 Answers4

2

const result = [0, 1, 2, 3, 4, 5].reduce(
    (acc, val) => {
        if (acc[acc.length - 1].length < 2) {
            acc[acc.length - 1].push(val);
        } else {
            acc.push([val]);
        }

        return acc;
    },
    [[]],
);

console.log(result);
Nikita Madeev
  • 4,284
  • 9
  • 20
0

This snippet creates an array with a number of indexes, then maps the starting index of each division and uses that index in the next map to take a slice of the original array based on the given size.

const value = [0, 1, 2, 3, 4, 5];

const arrayChunks = (array, size) => Array(Math.ceil(array.length / size)).fill()
  .map((entry, index) => index * size)
  .map(begin => array.slice(begin, begin + size));
  
let result = arrayChunks(value, 2);
console.log(result);
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
0

Or, more imperative approach

function convert(arr) {
    const nextArray = [];
 
    for (let i = 0; i < arr.length; i += 2) {    
        // Handle case where there is no pair for the element
        // Can be removed if not required
        const isLastElement = arr.length === i + 1;

        if (isLastElement) {
           nextArray.push([arr[i]]);
        } else {
           nextArray.push([arr[i], arr[i + 1]]);        
        }
        
    }

    return nextArray;
}

const result1 = convert([1,2,3,4]);
const result2 = convert([1,2,3]);

console.log('Even', result1);
console.log('Odd', result2);
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
0

Another way with foreach:

const data = [0,1,2,3,4,5]

let subArray = [];
let result = []
data.forEach((val, i) => {
  subArray.push(val);
  if(subArray.length == 2 || i == (data.length - 1)) {
    result.push(subArray);
    subArray = [];
  }
})

console.log(result)
Howäms
  • 141
  • 4