0

Say I have an array

var originalArray = [1,2,3,4,5,6,7]

I want to display to apply function orderToColumn (originalArray, numberofcolumn) to get a return value like so

Array [ 1, 4, 7, 2, 5, undefined, 3, 6, undefined ]

the point being I want to be able to display my array in the following format:

1 4 7
2 5
3 6

Heres my attempt so far: https://jsfiddle.net/042o7rv9/ The array could be of any size and the numberofcolumn>=1.

3
  • Can you give another example with a longer or a shorter array? Commented Sep 16, 2016 at 20:19
  • Does originalArray always start with 1 and is it always sorted? In other words, why is there no gap for the missing 0? Commented Sep 16, 2016 at 20:31
  • nah the array could be objects, i used sorted numbers simply for explanation purposes. anyways i figured it out on my own. seemed to be more of an bootstrap/css error when rendering rather than algorithm error Commented Sep 16, 2016 at 20:37

2 Answers 2

2

You can do something like this.

var a = [1,2,3,4,5,6,7];
function orderToColumn(arr,col){
  var len = col*Math.ceil(arr.length / col);
  console.log(len);
  var newArr=[];
  for(var i = 0;i<col;i++){
    for(var j=0;j<len/col;j++){
      newArr.push(arr[j*col+i]);
    }
  }
  return newArr;
}
var b = orderToColumn(a,3);
console.log(b); // [1, 4, 7, 2, 5, undefined, 3, 6, undefined]
Sign up to request clarification or add additional context in comments.

Comments

0

You might do functionally as follows;

function columnize(a,n){
  var count = Math.ceil(a.length/n);
  return a.reduce((p,c,i) => i%count === 0 ? p.concat([[c]]) : (p[p.length-1].push(c),p),[]);
}

var originalArray = [1,2,3,4,5,6,7],
           result = columnize(originalArray,3);
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.