I am trying to use CSS column to replicate a masonry grid and it works perfectly except for the order. To make this work I want to take my array of items and re order the items so to make them read from left to right.
I know how many columns there are column count(may change from 2- to 4) and I have an array of data but I am not sure on the best way to shift this index’s of each item to the correct new index example shown below. I thought I could user filter but I cant get the logic to work.
const countArray = Array.from(Array(columnCount).keys());
for(let i= 0; i < countArray.length; i++) {
returnArray = returnArray.concat(
dataList.filter((value, index,) =>{
return (index % i === i - 1)
})
);
}
DEFAULT
1 | 4
2 | 5
3 | 6
NEW ORDER
1 | 2
3 | 4
5 | 6
>Solution :
I think the best way to do this is to break the data into "buckets" to order them based on the number of columns you have, then flatten those buckets back into a single-dimensional array for output/display purposes. The below solution will handle any data length and any number of columns and return a re-ordered array based on the number of columns you have. Hope this helps.
let data = [1, 2, 3, 4, 5, 6];
function dataColumnReorder (data, numColumns) {
// generate a list of "buckets" to order the items
let buckets = [];
for (let i = 0; i < numColumns; i++) {
buckets.push([]);
}
// fill the buckets, then flatten so all the data ends up in 1 flattened array
let reordered = data.reduce((res, curr, index) => {
// determine which bucket the item goes into based on index
let bucketIndex = index % numColumns;
res[bucketIndex].push(curr);
return res;
}, buckets).flat();
return reordered;
}
console.log(dataColumnReorder(data, 1));
console.log(dataColumnReorder(data, 2));
console.log(dataColumnReorder(data, 3));
console.log(dataColumnReorder(data, 4));