通过匹配元素值

时间:2017-05-20 14:43:13

标签: javascript arrays

我有一个数组arr = ['14:00', '15:00', '16:00', ...]

我想旋转数组,使得最接近实际时间的时间元素是第一个。

我找到了一个在这里使用函数

旋转数组的函数JavaScript Array rotate()
function arrayRotate(arr, count) {
  count -= arr.length * Math.floor(count / arr.length)
  arr.push.apply(arr, arr.splice(0, count))
  return arr
}

但我不知道如何确定count参数以确保第一个元素最接近实际时间。

3 个答案:

答案 0 :(得分:1)

如果你想把实际时间拿到顶部,剩下给定的订单,你可以使用

  1. Array#splice用于获取所需项目并将其移至数组中的第一位。
  2. var array = ['14:00', '15:00', '16:00', '17:00'],
        actual = '16:00';
    
    array.unshift(array.splice(array.indexOf(actual), 1)[0]);
    console.log(array);

    1. 或者将实际时间移到顶部进行排序,然后按字符串排序其余部分。
    2. var array = ['14:00', '15:00', '16:00', '17:00'],
          actual = '16:00';
      
      array.sort(function (a, b) {
          return (b === actual) - (a === actual) || a.localeCompare(b);
      });
      
      console.log(array);

答案 1 :(得分:0)

要获得实际值,您可以使用new Date().getHours()

let arr = [];
       
for (var i=0; i<24;i++) {
  arr[i] = i+':00';
}

// console.log(arr) ["0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"]

function arrayRotate(arr, count) {
  count -= arr.length * Math.floor(count / arr.length)
  arr.push.apply(arr, arr.splice(0, count))
  return arr
}

let hour = new Date().getHours();

/// console.log(hour); 12

arrayRotate(arr, hour);

// console.log(arr); ["12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00"]

答案 2 :(得分:0)

  var array = ["0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"];
  var actual = '16:21';

  // calculates the difference between 2 timestamps in hh:mm format
  function timeDifference(time1, time2){
    var t1 = time1.split(':'), t2 = time2.split(':');
    return Math.abs((t1[0]*60 + t1[1]) - (t2[0]*60 + t2[1]));
  }

  // loops over the array and compares each time the first element with the actual time
  // until a timestamp is found where the difference between the actual time and that one
  // is less or equal to 30 minutes
  function closestTime(array, actual){
    var diff = timeDifference(actual, array[0]);
    var i = 1;
    while (i < array.length && diff > 30) {
      // add the first element to the end of the array
      var b = array.shift();
      array.push(b);
      
      diff = timeDifference(actual, array[0]);
      i += 1;
    }
    return array;
  }

  console.log(closestTime(array, actual));

假设您以此格式获得实际时间,并且所有时间戳都在00:00到23:00之间,您可以执行此操作。 (我没有使用你提到的功能)。我对javascript还不是很满意,所以如果有人可以改进代码,请告诉我。