Javascript数组比较元素

时间:2018-02-16 12:41:29

标签: javascript

我有一个包含日期的数组,我想从每个月的数组中获取最后一个值。我怎样才能做到这一点?我有这段代码:

for (var i = 0; i < vm.openDatesToSave.length; i++) {
            var c = vm.openDatesToSave[i].getMonth();
            for (var j = i+1; j < vm.openDatesToSave.length; j++) {
                var d = vm.openDatesToSave[j].getMonth();
                if (d === c) {
                    a.push(vm.openDatesToSave[j]);
                }
            }
        }

enter image description here

例如,我想采取09年1月9日,2月6日和3月14日。

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var dates = [new Date('2018-05-12'), new Date('2018-04-03'), new Date('2018-05-04')];

var result = dates.reduce((acc, item) => {
   const month = item.getMonth(); 
   acc[month] = item;
   return acc;
},{})

console.log(Object.values(result));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var dates = [
	new Date( '2018-02-14' ),
	new Date( '2018-01-17' ),
	new Date( '2018-02-06' ),
	new Date( '2018-01-09' ),
	new Date( '2018-03-14' )
];
// We want to transform an array of dates into a shorter summary. So we use reduce to turn multiple values into less values.
// By using a object as the output, we get an easy summary which can be turned back into an array if needed.
var lastDatesPerMonth = dates.reduce( function( months, date ) {
	// months are zero-based, so + 1
	var month = date.getMonth() + 1;
	// Always overwrite the correct month with the new date.
	months[ month ] = date;
	return months;
}, {} );

console.log( lastDatesPerMonth );

答案 2 :(得分:0)

如果你正在使用lodash,那么

lastDays = _.map(_.groupBy(dates, d => d.getMonth()), _.last)

否则考虑使用它。

咆哮:我不明白为什么SO总是喜欢复杂而脆弱的临时解决方案来建立一个高效且经过测试的库,最后咆哮;)