12

I'm using Array.prototype.map.call to store in an array a bunch of node list objects:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect();
         }
    }
}

However, I also want to store the order in which this elements appear in the DOM, and I don't know how to do that.

I know that I'm storing this in an array, and the order would be the index of the array. For example:

var listings = getListings();
console.log(listings[0]); // rank #1
console.log(listings[1]); // rank #2
// etc...

but I'm inserting the json object in a database, and the easiest way to store the "rank" information is by creating a property "rank" in my object, but I don't know how to get the "index" of the current array.

Something like:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect(),
             rank: magicFunctionThatReturnsCurrentIndex() // <-- magic happens
         }
    }
}

Any help pointing me to the right direction will be greatly appreciated! Thanks

Guillaume Lhz
  • 904
  • 5
  • 16
ILikeTacos
  • 17,464
  • 20
  • 58
  • 88
  • I think `document.querySelectorAll('li.g')` should return elements right in the correct order, i.e. how they appear in DOM. – VisioN Nov 15 '13 at 14:47
  • Yes it does, but is there any way to get the numerical value? I have the elements in the current order, but I want to have an attribute in my JSON object with its numerical value. – ILikeTacos Nov 15 '13 at 14:48

1 Answers1

22

The MDN documentation says:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

So

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e, rank) { // magic 
         return {
             rectangle: e.getBoundingClientRect(),
             rank: rank // <-- magic happens
         }
    }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • 2
    I read that page over and over, and for whatever reason I never noticed that the index was also being passed. Thanks! – ILikeTacos Nov 15 '13 at 15:11