找到数组中的前k个元素

时间:2015-02-20 14:45:24

标签: javascript jquery arrays

我有一个格式为:

的数组
var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]]

为了根据第二个参数找到前3个元素,我对数组进行排序。所以为此我使用下面的代码:

 series.sort( function(a,b) {
        if (a[1] === b[1]) {
            return 0;
    }
    else {
         return (a[1] < b[1]) ? 1 : -1;
    }
});

哪个工作正常。那么如果我想找到前三名,我总能选择[0,2]。但是,如果第4个值等于3,那么我会想念它。在这种情况下,如果我要求前3,输出应该是[[horse,1],[cat,2],[dog,4],[dragon,4]因为龙和狗具有相同的值(4)。所以,我想知道是否有一些我可以使用的库或一些有效的算法来返回前3个值,这并不一定意味着返回前3个元素数组?

3 个答案:

答案 0 :(得分:3)

只需建立一个清单:

var top = [];
top.push(series[0]);
top.push(series[1]);
for (var i = 2; i < series.length && series[i][1] == series[2][1]; ++i)
  top.push(series[i]);

概括(稍微):

function top(series, k) {
  var top = [];
  for (var i = ; i < k - 1; ++i)
    top.push(series[i]);
  for (; i < series.length && series[k-1][1] == series[i][1]; ++i)
    top.push(series[i]);
  return top;
}

答案 1 :(得分:0)

var series = [["horse",1],["cat",2],["dog",4],["dragon",4],["cow",6]]
num = 3;
var arr = [];
for(var i=0; i<series.length; i++)
{
var curr = series[i][1];
var next = series[i][1];
    if(i<num)
    {
     arr.push(series[i]);
    }
    else if(curr==next)
    {
     arr.push(series[i]);
        break;
    }    
}
console.log(arr);

答案 2 :(得分:0)

所以我会制作第二个数组(长度为3)并循环遍历初始数组。当前三个项目应自动添加到数组中。然后当我们遍历第一个数组并找到高于最低值的值时,我们删除最低值并将新项目放在新数组中的适当位置。

var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]];
function top3(a){
  // Create a new Array to hold the top values
  var top = [a[0], a[1], a[2]]; // Initialize it with the first three items
  for(var i=3;i<a.length;i++){
    /* Find the minimum value and its position */
    var min = top[0][1];
    var min_pos = 0;
    for(var e=1;e<3;e++){
      if(top[e][1]<min){
        min = top[e][1];
        min_post = e;
      }
    }
    /* If larger than the top arrays minimum */
    if( a[i][1] > min ){
      /* remove the top arrays min */
      top.splice(min_pos, 1);
    }
    /* Add the new item into the top array */
    top.push(a[i]);
  }
  /* Now our "top" array has the items with the top 3 values, if you want them sorted use a bubble sort here, if not just return "top" */
  bubbleSortByIndex(a, 1); // Sorts by the second item in an array or arrays
  return top;
};
/*
    Bubble Sort Algorythm adapted from http://en.wikipedia.org/wiki/Bubble_sort
*/
function bubbleSortByIndex(a, i){
  var swapped;
  do {
    swapped = false;
    for(var e=1;e<a.length-1;e++){
      if( a[e-1][i] > A[e][i]){
        swapped = true;
        var temp = a[e-1];
        a[e-1] = a[e];
        a[e] = temp
      }
    }
  } while (swapped);
  return a;
}
top3(series);

这使原始数组保持原样,只查找前三项,并对其进行排序。如果你想要对整个原始数组进行排序,那么只需调用bubbleSortByIndex(series, 1)并忽略整个&#34; top3()&#34;功能

相关问题