1

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 not the smallest value anymore).

But in my tests, it remains the same.

Community
  • 1
  • 1
jgthms
  • 864
  • 8
  • 18

1 Answers1

2

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks. That is exactly the function I was looking for. I was afraid, though, of not being able to access the _index_ of that value, but you showed me how. One question: what does the 'null' do in the apply() function? – jgthms Oct 16 '11 at 19:51
  • `.apply` accepts two arguments: The `this` keyword of the called function will be set to the first argument, and the list of arguments is specified through the second argument. In this case, the `this` keyword is irrelevant, and can be set to anything. See also: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply – Rob W Oct 16 '11 at 19:56
  • Keep in mind that older versions of IE don't have Array.indexOf() so you will have to shim that method if you want to use it in all browsers. – jfriend00 Oct 16 '11 at 20:08