开发者

Double 'each' loop to find the smallest value in an Array

开发者 https://www.devze.com 2023-04-13 04:26 出处:网络
I\'m trying to implement the Pinterest wall, as described here : how to replicate pinterest.com's absolute div stacking layout

I'm trying to implement the Pinterest wall, as described here : how to replicate pinterest.com's absolute div stacking layout

Anyway, I'm stuck at one point where I need to find the index of the smallest value in an Array, but at the same time, add the height of my current block to that value (so that the smallest value isn't always the same).

var grid = new Array(4); // 4 as example

// Add values to the Array
$.each(grid, function(j) {
    grid[j] = j;
});
var smallest_index = 0;
var smallest_value = grid[0];

// Find the index of the smallest value in the Array
SmallestValueIndex = function() {
    $.each(grid, function(i, v) {
        if (v < smallest_value) {
            smallest_index = i;
            smallest_value = v;
        }
    });
}

// Go through all my '<div>' and add the height to the current smallest value
$.each(blocs, function() {
    SmallestValueIndex();
    var h = $(this).height();
    grid[smallest_index] += h;
});

Each time, the smallest value should be different because I add the height to the previous smallest value (so it's 开发者_如何学JAVAnot the smallest value anymore).

But in my tests, it remains the same.


Try this code. It uses the native Math.min function, rather than a inefficient jQuery loop:

$.each(blocs, function() {
    var lowest = Math.min.apply(null, grid);
    var index = grid.indexOf(lowest);
    grid[index] += $(this).height();
}

First, Math.min() gets the lowest number out of all grid elements. Then, grid.indexOf() is used to find the position of this element. Finally, the height is added to the element in grid at index index.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号