Ela
Ela

Reputation: 879

Javascript array compare elements

I have an array with dates and I want to take the last value from array for each month. How can I do that? I have this code:

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

For example, I want to take Jan 09, Feb 06 and Mar 14.

Upvotes: 0

Views: 103

Answers (3)

georg
georg

Reputation: 215059

If you're using lodash, then

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

otherwise consider using it.

rant: I fail to see why SO keeps preferring convoluted and fragile ad-hoc solutions to an established, efficient and tested library, end rant ;)

Upvotes: 0

zabusa
zabusa

Reputation: 2719

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));

Upvotes: 2

Shilly
Shilly

Reputation: 8589

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 );

Upvotes: 1

Related Questions