返回数组中最近值的索引

时间:2014-09-15 18:11:11

标签: javascript

我有这个:

var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];

将最近值的索引返回给另一个变量的可读方式是什么?

例如:

变量= 1应返回{ low: 3, high: 1 }

7 个答案:

答案 0 :(得分:4)

几乎与排序一样简单但更快(O(n)):

const nearest = (arr, n) => arr.reduce((r, x) => ({
  lo: ((x < n) && (x > r.lo) ? x : r.lo),
  hi: ((x > n) && (x < r.hi) ? x : r.hi)
}), { lo: -Infinity, hi: Infinity })

const mapIndexOf = (obj, lookup) => Object.keys(obj).reduce(
  (a, v) => ({ ...a, [v]: lookup.indexOf(obj[v]) }), {}
) 

const scores = [0.7, 1.05, 0.81, 0.96, 3.2, 1.23]

console.log(mapIndexOf(nearest(scores, 1), scores))

答案 1 :(得分:2)

(O(n*log(n))和简单:

const nearest = (arr, val) => (sorted => (indexOfVal => ({
  lo: sorted[indexOfVal - 1],
  hi: sorted[indexOfVal + 1]
}))(sorted.indexOf(val)))([...arr, val].sort())


const mapIndexOf = (obj, lookup) => Object.keys(obj).reduce(
  (a, v) => ({ ...a, [v]: lookup.indexOf(obj[v]) }), {}
) 

const scores = [0.7, 1.05, 0.81, 0.96, 3.2, 1.23]

console.log(mapIndexOf(nearest(scores, 1), scores))

答案 2 :(得分:0)

循环遍历数组,从变量中减去值,比较,然后记录最接近的值。这是一个简单的例子:

&#13;
&#13;
var value = 1;
var scores = [0.7, 1.05, 0.81, 0.96, 3.2, 1.23];
var ret = {};

for(var i = 0, len = scores.length; i < len; i++){
  var comp = scores[i] - value;
  if(comp > 0){
    if(!ret.high){
      ret.high = i;
    }
    else if(scores[i] < scores[ret.high]){
      ret.high = i;
    }
  }
  else if(comp < 0){
    if(!ret.low){
      ret.low = i;
    }
    else if(scores[i] > scores[ret.low]){
      ret.low = i;
    }
  }
  else{
    ret = {
      low: i,
      high: i
    };
    break;
  }
}

document.getElementById('result').innerHTML = 'high: '+ret.high+' low: '+ret.low;
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这样:

var lower = function(a,b){return a.element > b.element ? b : a; };
var higher = function(a,b){return a.element > b.element ? a : b; };
var withIndex = function(element,index){ return {element: element, index: index}; };
var nearest = function(array, limit) {
  var lowerValues = array.map(withIndex).filter(function(a){ return a.element<limit });
  var higherValues = array.map(withIndex).filter(function(a){ return a.element>limit });
  return {
    low: lowerValues.reduce(higher).index, 
    high: higherValues.reduce(lower).index
  };
}

答案 4 :(得分:0)

var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];
var lowIndex = 0;
var highIndex = 0;
var currentLow = 0;
var currentHigh = 0;
var temp = 0;
var variable = 2;
for(var i = 0; i < scores.length; i++)
{
    temp = variable - scores[i];
    if((currentLow == 0) && (temp > 0))
    {
        currentLow = temp;
    }
    if((currentHigh == 0) && (temp < 0))
    {
        currentHigh = temp;
    }
   if((temp >= currentHigh) && (temp <= 0))
   {
      highIndex = i;
      currentHigh = temp;
   }
   if((temp <= currentLow) && (temp >= 0))
   {
      lowIndex = i;
      currentLow = temp;
   }
}
window.alert("Low:" + lowIndex + "  High:" + highIndex);

此代码有效,您可以看到最新的逻辑。

答案 5 :(得分:-1)

// for storing greater values and their indeces   
var gtVals = {
    val : [],
    ind : []
};

// for storing lesser values and their indeces 
var ltVals = {
    val : [],
    ind : []
} 

var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];

function highLow(value){
     var val = parseFloat(value);

         for(var i = 0; i < scores.length ; i++){
            if(scores[i] > val ){
                gtVals.val.push(scores [i] - val );
                gtVals.ind.push(i );
           }
        else{
             ltVals.val.push(val - scores[i] );
             ltVals.ind.push(i );
         }

     }
    var higherindex = gtVals.ind[gtVals.val.indexOf((Math.min.apply(Math, gtVals.val)))];
    var lowerindex = ltVals.ind[ltVals.val.indexOf((Math.min.apply(Math, ltVals.val)))];
    return {
        low: lowerindex,
        high :  higherindex
    };
}

console.log(highLow(1));

http://jsfiddle.net/2q572hxj/3/

答案 6 :(得分:-1)

对于喜欢perl,汇编或正则表达式的人来说,这里是一个靠近单行的解决方案:

var compV = 1;
var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];

for(var h=0,l=0,i=0,tmp=0,lV=Number.MAX_VALUE,hV=lV; i < scores.length; i++) {
   tmp=compV-scores[i];tmp>0 && tmp<lV ? (l=i,lV=tmp) : tmp<0 && -tmp<hV ? (h=i,hV=-tmp) : 0; }

l(小写“L”)保存最低值的索引,h(小写“H”)保存最高值的索引。玩得开心:))