2012-06-13 12 views
-2

我正在尋找一個函數,該函數將根據已知對象值從對象數組中搜索最近的2個元素。如果存在直接匹配,該函數將返回2個最接近的元素的索引或一個索引。它會通過每個元素中的p變量進行搜索。通過鍵在數組中找出最接近的2個元素

(它是安全的假設p變量不會出現一次以上)

var orbit = [ // p is percent 
    { p: 0, x: 0, y: 0, z: 1.2 } 
    { p: 30, x: 30, y: 100, z: 0.5 } 
    { p: 45, x: 100, y: 30, z: 0.7 } 
    { p: 75, x: 60, y: 0, z: 1.0 } 
    { p: 100, x: 0, y: 0, z: 1.2 } 
]; 

function ValueToIndexes (value) { 
    return [close1, close2]; 
}; 

如果該值被60它將返回[2,3]
如果該值是30,將返回[1]

+1

如何將60回[2,3]請讓問題更清楚。 – DhruvPathak

+0

你的問題根本不清楚 – Imdad

+0

當他說[2,3]時,我相信他在談論軌道陣列中物體的指數。 – Luke

回答

1
var ValueToIndices = function (orbit, value) { 

    var 
     /* storage for distances */ 
     distances = [], 

     /* sort helper */ 
     sortByDistance = function (a, b) { 
      return a.d - b.d; 
     }; 

    /* iterate over orbit */ 
    for (var i = 0; i < orbit.length; i++) { 

     /* a direct match returns immediately */ 
     if (orbit[i].p === value) { 
      return [i]; 
     } 

     /* else collect all distances to the value */ 
     distances.push({ 
      i: i, 
      d: Math.abs(orbit[i].p - value) 
     }); 
    } 

    /* sort the distances */ 
    distances.sort(sortByDistance); 

    /* return the indices of the first two */ 
    return [distances[0].i, distances[1].i]; 
}; 
+0

這正是我所尋找的,這是解決問題的一種非常有創意的方式。 –

1

像這樣的東西可能:

function ValueToIndexes(orbit, value) { 
    var sorted = orbit.sort(function (obj1, obj2) { 
     return Math.abs(obj1.p - value) - Math.abs(obj2.p - value); 
    }); 

    if (sorted[0].p === value) 
     return [sorted[0]]; 

    return [sorted[0], sorted[1]]; 
};