Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 查找最短持续时间_Javascript_Time_Momentjs_Duration - Fatal编程技术网

Javascript 查找最短持续时间

Javascript 查找最短持续时间,javascript,time,momentjs,duration,Javascript,Time,Momentjs,Duration,我有一个数组的持续时间字符串如下,并希望找到最短的时间 group = ["41:04", "54:50", "01:03:50"] // note this is mix of **mm:ss** and **HH:mm:ss** 我用的是瞬间: group.map(tid => moment.duration(tid,'hh:mm:ss').asSeconds()); 但它将前两个元素解释为“hh:mm”而不是“mm:ss”,结果是: [147840, 197400, 3830]

我有一个数组的持续时间字符串如下,并希望找到最短的时间

group = ["41:04", "54:50", "01:03:50"] // note this is mix of **mm:ss** and **HH:mm:ss**
我用的是瞬间:

group.map(tid => moment.duration(tid,'hh:mm:ss').asSeconds()); 
但它将前两个元素解释为“hh:mm”而不是“mm:ss”,结果是:

[147840, 197400, 3830]
然而,第一个元素“41:04”是最短的持续时间

有什么方法可以利用这个时刻来正确处理这个问题吗?或者,找到最短持续时间的最佳方法是什么


请注意,如果我自己将零连接到字符串(即,00:41:04),它将是正确的

您可以使用简单的数学计算经过的秒数,而无需使用任何库。 比如,

41:04 = 41 * 60 + 04
01:03:50 = 01 * (60 ^ 2) + 03 * 60 + 50
创建简单的函数来计算经过的
秒数

const getSeconds = str => {
  const sp = str.split(":");
  let sum = 0;
  sp.map((d, k) => {
    sum += Number(d) * 60 ** (sp.length - 1 - k);
  });
  return sum;
};
现在,您可以在阵列中循环以获得秒数

const min = group.reduce((d, k) => {
  const a = getSeconds(d),
      b = getSeconds(k);
  return  a < b ? d : k; 
});
const min=group.reduce((d,k)=>{
常数a=getSeconds(d),
b=秒(k);
返回a
作为一个整体,您可以查看下面的代码片段

const group=[“50:04”、“41:04”、“54:50”、“01:03:50”];
const getSeconds=str=>{
const sp=str.split(“:”);
设和=0;
sp.map((d,k)=>{
总和+=数字(d)*60**(sp.长度-1-k);
});
回报金额;
};
最小常数=组减少((d,k)=>{
常数a=getSeconds(d),
b=秒(k);
返回a控制台日志(分钟)
请注意,如果我自己将零连接到字符串(即00:41:04),它将是正确的。
。那你为什么不做呢?排序/比较规则1:每个项目必须是同一类型的。听起来你已经知道答案了!或者,如果字符串只有5个字符而不是8个字符,您可以只检查映射函数的字符串长度,并将不同的模式传递给矩。您可以用空字符串替换所有的
,然后对结果字符串使用
parseInt
,然后进行比较。但这感觉像是一个黑客