Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
I want to reduce array so I have its' values in 'columns' where the first value lives in the first column, the second one in the second, etc. until it wraps, so that for example the fourth value is in the first of three columns.
>> [1, 2, 3, 4, 5, 6, 7].in_columns(3) => [[1, 4, 7], [2, 5], [3, 6]]
A functional one-liner:
a = [1, 2, 3, 4, 5, 6, 7] cols = 3 res = [...Array(cols).keys()].map(c => a.filter((_, i) => i % cols === c)); console.log(res)
Add a comment
You could reduce the array by taking the remainder with the wanted count.
Array.prototype.inColumns = function (count) { return this.reduce((r, v, i) => ((r[i % count] = r[i % count] || []).push(v), r), []); } console.log([1, 2, 3, 4, 5, 6, 7].inColumns(3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can define a new in_columns method for the Array.prototype, using simple for loops:
in_columns
Array.prototype
Array.prototype.in_columns = function(n) { var result = new Array(n).fill().map(() => []); for (let i = 0; i < this.length; i++) { result[i % n].push(this[i]); } return result; } console.log([1, 2, 3, 4, 5, 6, 7].in_columns(3));
You can use below reducer to achieve that
const arr = [1, 2, 3, 4, 5, 6, 7]; const toColums = (arr, count) => { return [...arr.reduce((a, b, i) => a.set(i % count, (a.get(i % count) || []).concat(b)), new Map).values()]; }; console.log(toColums(arr, 3));
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.