Saber 酱的抱枕

Fly me to the moon

08/6
2016
学习

JavaScript对日期排序

假设现在获得了一些格式化的时间/日期字符串,如何用JavaScript对其排序呢?

理想的办法就是用Date.parse()方法将这些字符串解析为时间,直接比较它们的毫秒数。示例如下:

function sortDate(sortby) {
    return function(object1, object2) {
        var value1 = Date.parse(object1);
        var value2 = Date.parse(object2);
    	if(value1>value2){
    		return (sortby==="desc")?-1:1;
    	}else if(value1<value2){
    		return (sortby==="desc")?1:-1;
    	}
    }
}
var a=["2017/4/20","2016/6/3","2016/7/1","2016/7/27","2017/8/4","2016/10/13","2016/12/27","2017/1/14","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/2/3","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/1","2017/3/23","2017/3/31","2017/5/19","2017/5/19","2017/6/2","2017/6/24","2017/6/24","2017/6/24","2017/9/1","2017/9/5","2017/12/12","2018/2/19","2018/9/26","2017/5/19","2017/3/9","2017/7/14","2017/5/19","2017/5/19"];
a.sort(sortDate("desc"));

结果如下:

上例定义了一个sortDate函数,我们在数组的sort方法里将它作为参数。如果不手动设置排序参数为desc,那么这个函数将始终按升序排序。

标准的时间/日期格式如下:

"2017/4/20 16:20:30"

当然,只用一部分,或者改变下连接符,也是可以解析的。
Read More →

JavaScript对日期排序

05/28
2016
学习

JavaScript根据对象的属性排序

JavaScript的数组有个排序方法——sort()。如果数组里的项是直接值,直接使用sort()就可以进行排序。但如果数组项是object,直接用sort()排序就无效了。此时我们可以根据object的属性来排序。

var a=[
	{
		"name":"saber",
		"height":154
	},
	{
		"name":"Rin",
		"height":159
	},
	{
		"name":"Sakura",
		"height":156
	}
];
function sortByProperty(propertyName) {
	return function(object1, object2) {
		var value1 = object1[propertyName];
		var value2 = object2[propertyName];
		if (value2 < value1) {		//升序
			return 1;
		} else if (value2 > value1) {
			return -1;
		} else {
			return 0;
		}
	}
}
a.sort(sortByProperty("height"));

如上代码,定义了一个排序函数sortByProperty,传递了属性进去就根据什么属性的值排序。

上面代码得到的结果是升序,如图:

JavaScript根据object对象的属性排序

saber最矮我不服!

如果想改成降序排列,将sortByProperty函数return 1改成-1,return -1改成1就行了。

JavaScript根据对象的属性排序