const waterfallify = (heightList, columnCount, setPositionCallback) => {
const result = []
const totalHeightArr = new Array(columnCount).fill(0)
heightList.forEach( (heightItem, index) => {
const minIndex = getMin(totalHeightArr).index
if(result[minIndex]) {
result[minIndex].push(index)
}else {
result[minIndex] = [index]
}
totalHeightArr[minIndex] += heightItem
setPositionCallback && setPositionCallback(index, minIndex)
})
return result
}
const getMin = (arr) => {
let min = Number.POSITIVE_INFINITY
let minIndex = -1
arr.forEach((item, index) => {
if(item < min) {
min = item
minIndex = index
}
})
return {
index: minIndex,
number: min
}
}
const imagelist=[
{src:'',prview_height:228},
{src:'',prview_height:345},
{src:'',prview_height:124},
{src:'',prview_height:300},
{src:'',prview_height:400},
{src:'',prview_height:200},
{src:'',prview_height:209}
]
const list = imagelist.map(image => image.prview_height)
let result = waterfallify(list,2,(index,index2) =>{})
result = result.map(resultItem => {
return resultItem.map(item => {
return imagelist[item]
})
})
document.write('<hr>')
document.write(result.map((item,index) => `第${index}列:${item}`).join('<br>'))
console