在Javascript中对这个字符串列表进行排序的最简单方法是什么?

时间:2017-05-18 23:05:16

标签: javascript sorting

list = ["Conversation With Bob May 10, 2017 13:05", 
        "Conversation With Bob May 10, 2017 9:22", 
        "Conversation With Alice May 12, 2017 4:12",
        "Conversation With Alice May 8, 2017 3:59",
        "Conversation With Kevin December 12, 2017 7:55",
        "Conversation With Tom January 5, 2017 16:00",
        "Conversation With Alice, Bob, Kevin February 5, 2017 21:00",
        "Conversation With Alice, Kevin March 12, 2017 9:45"]

我想首先按照“与Alice交谈”部分按字母顺序对此列表进行排序,然后按日期/时间排序。

我知道我必须做一些事情:

list.sort(
    function(a,b) {
        //DO SOMETHING
    }
)

但我无法正确理解这一点。

编辑:抱歉,我的意思是javascript。

2 个答案:

答案 0 :(得分:1)

对于将日期字符串转换为Date对象,我建议你找一个为你做这个的库,为什么要重新发明轮子 - 在下面,我正在使用momentjs

var list = [
    "Conversation With Bob May 10, 2017 13:05",
    "Conversation With Bob May 10, 2017 9:22",
    "Conversation With Alice May 12, 2017 4:12",
    "Conversation With Alice May 8, 2017 3:59",
    "Conversation With Kevin December 12, 2017 7:55",
    "Conversation With Tom January 5, 2017 16:00",
    "Conversation With Alice, Bob, Kevin February 5, 2017 21:00",
    "Conversation With Alice, Kevin March 12, 2017 9:45"
];

var sorted = list.map(item => {
    let s = item.split(' '),
        d = s.splice(-4),
        date = moment(d.join(' '), 'MMMM do, YYYY h:mm').toDate(),
        text = s.join(' ');

    return { item, text, date };
})
.sort((a, b) => a.text.localeCompare(b.text) || (a.date - b.date))
.map(item => item.item);

console.log(sorted.join('\n'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>

答案 1 :(得分:0)

如果要按名称对此列表进行排序,只需找到第二个空格的索引,然后将1添加到该位置以查找名称的第一个字符。之后,您可以使用该char的ASCII值对字符串进行排序。否则,如果要按日期排序,则需要查找日期并将其转换为日期对象。然后,您可以简单地控制日期的时间戳来对字符串进行排序。