如何在JavaScript中获得每小时的最新心情

时间:2018-08-29 12:22:51

标签: javascript arrays

如何过滤数组以获取每小时的最新心情?

示例数据模型:

  var arr = [{
    mood: "normal",
    date: "29-7-2018",
    time: "9:24 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "9:34 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "9:40 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "10:14 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "10:46 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "2:04 pm"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "2:14 pm"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "3:01 pm"
  }
];

JsFiddle here

let l = arr.length;
/* console.log("length - " + l); */
let _time = formatAMPM(new Date()).split(":")[0];
arr = arr.filter(obj => obj.time.split(":")[0] != _time);
/* l = arr.length; */


/* for (i = l; i > 0; i--) {
  arr = arr.filter(obj => obj.time.split(":")[0] == _time);
  // console.log("--Fil elem--");
  // console.log(arr);
} */

console.log(arr);

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? "pm" : "am";
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? "0" + minutes : minutes;
  var strTime = hours + ":" + minutes + " " + ampm;
  return strTime;
}

3 个答案:

答案 0 :(得分:2)

您可以先按小时将项目分组,例如:

let arr = [...Your array of objects...];

let groupedByHour = arr.reduce(function(result, item) {
    let hour = item.time.split(':')[0];
    result[hour] = result[hour] || [];
    result[hour].push(item);
    return result;
}, {});

这将为您提供一个类似这样的对象:

{
    2:[
        {mood: "normal", date: "29-7-2018", time: "2:04 pm"},
        {mood: "normal", date: "29-7-2018", time: "2:14 pm"}
    ],
    3: [
        {mood: "normal", date: "29-7-2018", time: "3:01 pm"}
    ]
    // and so on...

}

现在您已将所有项目按小时分组,因此现在您可以遍历对象,并使用date字段按降序对数组进行排序,例如:

for(let key in groupedByHour) {
    groupedByHour[key].sort(function(a, b) {
        return a.time < b.time;
    });
}

现在,您将获得相同的对象,但是数组是有序的,因此将是这样的:

{
    2:[
        {mood: "normal", date: "29-7-2018", time: "2:14 pm"},
        {mood: "normal", date: "29-7-2018", time: "2:04 pm"}

    ],
    3: [
        {mood: "normal", date: "29-7-2018", time: "3:01 pm"}
    ]
    // and so on...

}

现在,在每个小时中,数组的第一项是最新的心情,因此,如果您希望从每个小时中获取所有最新的心情,则可以这样获取:

let moods = {};
for (let k in groupedByHour) {
    moods[k] = groupedByHour[k][0];
}

// Log them out
console.log(moods);

在此处检查console.log(每个键是一个小时,值是最新的心情)。

答案 1 :(得分:1)

对于moment.jslodash来说还不错,但是为了提高性能,您应该真正考虑采用另一种方式,例如通过数据库查询。

var arr = [{mood: "normal",date: "29-7-2018",time: "9:24 am"},{mood: "normal",date: "29-7-2018",time: "9:34 am"},{mood: "normal",date: "29-7-2018",time: "9:40 am"},{mood: "normal",date: "29-7-2018",time: "10:14 am"},{mood: "normal",date: "29-7-2018",time: "10:46 am"},{mood: "normal",date: "29-7-2018",time: "2:04 pm"},{mood: "normal",date: "29-7-2018",time: "2:14 pm"},{mood: "normal",date: "29-7-2018",time: "3:01 pm"}];

let moods = arr.map(o=>({mood:o.mood,datetime:moment(o.date + " "+ o.time,'DD-MM-YYYY hh:mm A')})).sort((a,b)=>a.datetime.valueOf() < b.datetime.valueOf())

moods = _.uniqWith(moods,(a,o)=>moment(o.datetime).startOf('hour').valueOf()===moment(a.datetime).startOf('hour').valueOf())

console.log(moods)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

答案 2 :(得分:1)

我通过将解决方案的骨架分解为功能,并使用清晰的名称和注释来破坏了它的框架。这些还没有完成,但是应该让您开始了解如何解决问题。

以下是步骤:

  • 按小时分组心情
    • 从心情对象的时间部分获取小时数
    • 如果之前已经看过那个小时,请添加心情
    • 否则,请在该小时内创建一个新数组
  • 查找每小时的最新心情
    • 返回该对象而不是对象数组。

var moods = [{
    mood: "normal",
    date: "29-7-2018",
    time: "9:24 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "9:34 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "9:40 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "10:14 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "10:46 am"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "2:04 pm"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "2:14 pm"
  },
  {
    mood: "normal",
    date: "29-7-2018",
    time: "3:01 pm"
  }
];

// takes time as a string and returns an hour as a string
//not finished
function getHour(timeAsString) {
  return "2";
}

// creates an object of arrays for each hour,
// one per hour
// ["1":[{...},{....}], ....
let groupMoodsByHour = (memo, current) => {
  const hour = getHour(current);
  if (memo[hour]) {
    memo[hour].push(current);
  } else {
    memo[hour] = [current]
  }
  return memo;
};

// gets the most recent object from an array of moodObjects
function getLatestHour(arrayOfMoods) {
  return arrayOfMoods[0];
}

let moodsByHour = moods.reduce(groupMoodsByHour,[]).map(getLatestHour);

console.log(moodsByHour);

这将无法正常工作,但应该是一个很好的开始。