Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

arrays - Javascript : Filter list by last time of day and return a single value

I have a list of times of text messages and I am trying to return the last text message sent on a particular day.

I am new to Javascript maybe this is easy but I just don't know how to do this This what I have tried I am completely clueless.

My Code:

    const texts = [

    {
        date: "27 Jan 2021",
        text: "Hey nice to see you",
        time: "12:22",
    },
    {
        date: "27 Jan 2021",
        feeling: "Cry",
        text: "All good you?",
        time: "16:26",
    },
    {
        date: "27 Jan 2021",
        text: "You too how's life treating you?",
        time: "12:26",
    },


]

const output = texts.filter(i=>i.time)

Desired Output:

const output = [
    {
     date: "27 Jan 2021",
     feeling: "Cry",
     text: "All good you?",
     time: "16:26",
   },
]
question from:https://stackoverflow.com/questions/65917675/javascript-filter-list-by-last-time-of-day-and-return-a-single-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sorting and then taking first / last depending on how you sorted is a popular way, but it's not the most efficient if the array is very large.

But you could use reduce to keep the accumulator with the maximum value.

eg.

const texts = [{"date":"27 Jan 2021","text":"Hey nice to see you","time":"12:22"},{"date":"27 Jan 2021","feeling":"Cry","text":"All good you?","time":"16:26"},{"date":"27 Jan 2021","text":"You too how's life treating you?","time":"12:26"}];
     
const result = texts.reduce((a, v) => {
  return v.time > a.time ? v : a;
});
 
console.log([result]);
 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...