它会提醒Masonry Grid的照片。
为什么4与1? - 以图形方式(3列)
|-----------|
| 4 | 3 | 2 |
|-----------|
| 1 | | |
|-----------|
为什么4用2和3用1? - 图形化(2列)
---------
| 4 | 3 |
---------
| 2 | 1 |
---------
const photos = [{
id: 1,
height: '50px',
photo: 'A'
}, {
id: 2,
height: '100px',
photo: 'B'
}, {
id: 3,
height: '150px',
photo: 'C'
}, {
id: 4,
height: '200px',
photo: 'D'
}];
let response = [];
const toColumns = (photos, columns) => {
/*
Response:
response = [
[
{
id: 4,
photo: 'D',
},
{
id: 1,
photo: 'A',
}
],
[
{
id: 3,
photo: 'C',
},
],
[
{
id: 2,
photo: 'B',
},
],
];
*/
};
toColumns(photos, 3);
答案 0 :(得分:1)
希望这是你想要的
const toColumns = (photos, columns) => {
photos = photos.reverse()
let response = []
for(let i = 0, l = photos.length; i < l; i++){
let j = i % columns
response[j] = response[j] || []
response[j].push(photos[i])
}
return response
}
const fromColumns = (columns) => {
let result = []
let i = j = 0, l = columns.length
while (1){
if(!columns[i][j]) break
result.push(columns[i][j])
if(++i >= l){
i = 0
j++
}
}
return result.reverse()
}
let photos = [1,2,3,4]
console.log(toColumns(photos, 3)) // [ [ 4, 1 ], [ 3 ], [ 2 ] ]
console.log(toColumns(photos, 2)) // [ [ 4, 2 ], [ 3, 1 ] ]
console.log(toColumns(photos, 1)) // [ [ 4, 3, 2, 1 ] ]
console.log(toColumns(photos, 5)) // [ [ 4 ], [ 3 ], [ 2 ], [ 1 ] ]
console.log(fromColumns(toColumns(photos, 2))) // [ 1, 2, 3, 4 ]