2017-04-26 12 views
0

내가 컬렉션을 가지고 값 동일한 날짜 시간을 사용하고 모든 시간 값을 합산하십시오.하면 모델은 다음과 같이 위치를

일부 컨텍스트를 제공하기 위해 기본적으로 우리 사이트에 세션을 넣는 사용자가 있으며, 모든 세션에는 그들이 플레이 한 시간이 기록되지만, 보통 하루에 약 10 세션을 사용합니다. 우리는 주어진 시간 동안이 모든 세션을 결합하여 그들이 그래프로 사용한 총 시간을 출력하고 싶습니다.

사용자가 연주 한 날을 기준으로 이러한 모델을 결합하는 방법을 알려주고 그 주어진 시간 동안 연주 한 모든 시간을 더할 수 있습니까? 고맙습니다!

+0

이러한 속성의 값은 무엇입니까? –

+0

어떤 종류의 datetime 형식입니까? 순간을 사용하고 있습니까? –

답변

0

이렇게하려면 몇 가지 다른 밑줄 방법을 조합하여 사용하십시오. 날짜순으로 그룹으로 그룹화하고, 원하는대로 정확하게 보이는 개체를 만들기위한지도를 만들고 항목을 합산하여 줄입니다. 이 모두가 의미

arrayOfProfileStats = [{ 
 
    defaults: { 
 
     sessionID: '1', 
 
     uID: '', 
 
     keySig: '', 
 
     tempo: '', 
 
     time: '00:10:00', 
 
     datetime: '01/01/2000' 
 
    } 
 

 
    }, 
 
    { 
 
    defaults: { 
 
     sessionID: '2', 
 
     uID: '', 
 
     keySig: '', 
 
     tempo: '', 
 
     time: '00:10:00', 
 
     datetime: '01/01/2000' 
 
    } 
 
    }, 
 
    { 
 
    defaults: { 
 
     sessionID: '3', 
 
     uID: '', 
 
     keySig: '', 
 
     tempo: '', 
 
     time: '00:10:00', 
 
     datetime: '01/02/2000' 
 
    } 
 
    } 
 
]; 
 

 
function msToHMS(ms) { 
 
    // 1- Convert to seconds: 
 
    var seconds = ms/1000; 
 
    // 2- Extract hours: 
 
    var hours = parseInt(seconds/3600); // 3,600 seconds in 1 hour 
 
    seconds = seconds % 3600; // seconds remaining after extracting hours 
 
    // 3- Extract minutes: 
 
    var minutes = parseInt(seconds/60); // 60 seconds in 1 minute 
 
    // 4- Keep only seconds not extracted to minutes: 
 
    seconds = seconds % 60; 
 
    return (hours + ":" + minutes + ":" + seconds); 
 
} 
 

 
function toMilliseconds(time) { 
 
    var a = time.split(':'); // split it at the colons 
 
    return ((parseInt(a[0]) * 60 * 60 + parseInt(a[1]) * 60 + parseInt(a[2])) * 1000); 
 
} 
 

 
var timeForEachDay = function() { 
 
    var grouped = (_.groupBy(arrayOfProfileStats, function(stat) { 
 
    return stat.defaults.datetime; 
 
    })); 
 

 
    return _.map(grouped, function(profileDate, key) { 
 
    // At this point we should have a new object that groups the profileStats by datetime 
 
    // Now we need to sum the times using reduce() 
 
    return { 
 
     [key]: msToHMS(_.reduce(_.map(profileDate, function(date) { 
 
     return toMilliseconds(date.defaults.time); 
 
     }), function(total, time) { 
 
     return total + time; 
 
     }, 0)) 
 
    }; 
 
    }); 
 
} 
 
console.log(timeForEachDay());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

+0

행운이 있나요? 당신이 이것을 볼 기회가 있었는지 확실하지 않지만 "00:10:05"와 같은 시간 형식을 사용하여 작동하게했습니다. – Chris

+0

죄송합니다. 몇 가지 밑줄 기능으로이 문제를 해결했습니다. 나는 그들을 게시 할 것이다. – user2796352

0

나는 부부가이 문제를 해결하는 방법을 강조 사용하게 알려줘. 첫 번째 함수는 컬렉션의 모든 모델을 필터링하여 수집 할 모델이 특정 날짜 이후인지 확인합니다. 두 번째 함수는 선택한 모든 모델을 정렬하고 재생 된 시간을 요약합니다.

filtered = this.filter(function (ProfileStat) { 
     //convert the current models datetime to unix 
     unixDateTime = Moment(ProfileStat.get("datetime")).valueOf(); 
     //convert the interval date to unix 
     intervalDate = Moment(intervalDate).valueOf(); 
     //only return the sessions that are ahead of the interval date 
     return unixDateTime >= intervalDate; 

     //iterate through each model returned from the filtered function and combine all the sessions for any given date 
    }).forEach(function(ProfileStat){ 
     //format the current model date time to MM/DD/YYYY 
     ProfileStat.attributes.datetime = Moment(ProfileStat.get('datetime')).format('MM/DD/YYYY'); 
     //store this datetime in a variable 
     var date = ProfileStat.attributes.datetime; 
     if (dateArray.indexOf(date) == -1) { 
      dateArray.push(date); 
      var obj = {datetime: date, timePlayed: ProfileStat.attributes.timePlayed,}; 
      resultArray.push(obj); 
     } 
     else { 
      resultArray[dateArray.indexOf(date)].timePlayed += ProfileStat.attributes.timePlayed; 
     } 
    });