Jack Jack - 6 months ago 6
Node.js Question

Change element array position to top

I have this function in NodeJS where i filter elements:

// Remove duplicates and expired
var data = (result[0].concat(result[1]).concat(result[3])).filter((event, index, self) => self.findIndex((t) => {
var eventDate = new Date(event.start_time);
return t.id === event.id && todayDate.setHours(0,0,0,0) <= eventDate.setHours(0,0,0,0);
}) === index)

// Remove invalid
return false;
} else {
return true;
}, result[2])

// Sort array by date
.sort(function(a,b) {
return new Date(a.start_time).getTime() - new Date(b.start_time).getTime();

// Filter promoted
event.promoted = true;
return true;
}, result[4]);

Now, in the last filter method I'm finding elements with ID from the lis(result [4]) and add to them property "promoted".

I also wanted to move all promoted events immediatly to the top of array since i have their index in array instead of firing another loop to this job.

How can i do this? Because using splice for me didn't work

Also any suggestion on quality of this function?

Thanks :)


You shouldn't use filter to change elements of array. There is map for that.

If you want to sort elements based on more than one property you could do it like this.

const invalid = result[2],
    promoted = result[4];

var data = result[0]
   .concat(result[1], result[3])
   .filter(dedup) //remove duplicated
   //set promoted flag
   .map(event => {
       event.promoted = promoted.indexOf(event.id) > -1
       return event
   //sort by promoted then by start_time  
   .sort((a, b) => (b.promoted - a.promoted) || (a.start_time - b.start_time))