开发者

Knowing position of a value under twodimensional Array

I have a SummaryData array as shown

var summaryData = [[0,100.34],[1,102.31],[2,131.08],[3,147.94],[4,172.55],[5,181.05],[6,180.08]];

My question is:

Is it possible to find out what the position of a value is?

(For example, how can I know wher开发者_Go百科e 147.94 is?) (I am expecting "3")


Update:

A more prototype-y way:

var result = summaryData.detect(function(item) { return item[1] === 147.94; });

alert(result[0]);

Or:

function getKey(arr, value) {
    var key = null,
        item;

    for (var i = 0; i < arr.length && !key; i++) {
        item = arr[i];
        if (item[1] === value) {
            key = i;
        }
    }
    return key;
}

Usage:

var n = getKey(summaryData, 147.94); // returns 3.


At the risk of doing your homework for you...

var summaryData = [[0,100.34],[1,102.31],[2,131.08],[3,147.94],[4,172.55],[5,181.05],[6,180.08]];

function findPosition(value, dataArray) {
  var a;

  for (var i=0, iLen=dataArray.length; i<iLen; i++) {
    a = dataArray[i];

    for (var j=0, jLen=a.length; j<jLen; j++){
      if (value == a[j]) {
        return i + ',' + j;
      }
    }
  }
}

alert(findPosition(131.08, summaryData)); // 2,1

The above returns the position of the first match.

Edit

I see now that you don't need to iterate over the second array, just look at the second value, so:

function findPosition(value, dataArray) {
  var a;

  for (var i=0, iLen=dataArray.length; i<iLen; i++) {
    a = dataArray[i];

    if (value == a[1]) {
        return a[0];
    }
  }
}

alert(findPosition(131.08, summaryData)); //2

Or if the data format is always as specified and there may be thousands of values, then it may be much faster to do:

function findPosition(value, dataArray) {
  var re = new RegExp('[^,],' + value);
  var m  = dataArray.join().match(re);
  return m && m[0].replace(/,.*/,'');

  // Or
  // return m && m[0].split(',')[0];

}


function getPosition(candidate) {
    var i = summaryData.length;
    while (i) {
        i -= 1;
        if (summaryData[i][1] === candidate) {
            return summaryData[i][0];
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜