This is an array of friends... with start and end of the friendship :) I want to sort the array by the computed duration of the friendship (end minus start)
const friends = [
{ name: "Michael", start: 1981, end: 2004 },
{ name: "Joe", start: 1992, end: 2008 },
{ name: "Sara", start: 1999, end: 2007 },
{ name: "Marcel", start: 1989, end: 2010 },
];
I was able to do this by first adding a friendshipDuration value and in a next step be sorting the array.
for (let i=0; i < companies.length; i ) {
// friends[i].friendshipDuration = friends[i].end - friends[i].start;
friends[i]["friendshipDuration"] = friends[i]["end"] - friends[i]["start"];
}
const sortedfriends = friends.sort(function(c1, c2) {
if(c1.friendshipDuration > c2.friendshipDuration) {
return 1;
} else {
return -1;
}
})
console.log(sortedfriends);
Yeah, but I would love to do this in one step... compute the friendshipDuration in the process of the higher order function sort().
const sortedfriends2 = friends.sort(function(c1, c2) {
const compDuration = friends.end - friends.start;
if(c1.compDuration > c2.compDuration) {
return 1;
} else {
return -1;
}
})
console.log(sortedfriends2);
There is this (c1, c1) => c1 - c2) tricky bit I'm reading about but I don't know where to put it. I'm a Javascript beginner and wanted to challenge myself with higher order functions;)
Help is very much appreciated.
CodePudding user response:
You need to calculate the duration for both c1 and c2 and then compare those two calculated values each time the comparison function is called.
const sortedfriends2 = friends.sort(function(c1, c2) {
const c1FriendshipDuration = c1.end - c1.start;
const c2FriendshipDuration = c2.end - c2.start;
if(c1FriendshipDuration > c2FriendshipDuration) {
return 1;
} else {
return -1;
}
});
console.log(sortedfriends2);
CodePudding user response:
You do not need to compute the friendship duration in advance, unless you need it for later. You can compute it on the fly as follows:
const friends = [
{ name: "Michael", start: 1981, end: 2004 },
{ name: "Joe", start: 1992, end: 2008 },
{ name: "Sara", start: 1999, end: 2007 },
{ name: "Marcel", start: 1989, end: 2010 },
];
const sortedfriends = friends.sort(
(a,b) => (a.end - a.start) - (b.end - b.start)
);
console.log( sortedfriends );
Need Duration?
Just in case you need friendshipDuration
for later, you can use Array#map
to compute it, followed by sorting:
const friends = [
{ name: "Michael", start: 1981, end: 2004 },
{ name: "Joe", start: 1992, end: 2008 },
{ name: "Sara", start: 1999, end: 2007 },
{ name: "Marcel", start: 1989, end: 2010 },
];
const sortedfriends = friends.map(
f => ({...f,friendshipDuration:f.end - f.start})
).sort(
(a,b) => a.friendshipDuration - b.friendshipDuration
);
console.log( sortedfriends );