JSFiddle - React, Tailwind, and code Playground
by Stepan Parunashvili
JavaScript
// Custom sorter
// ------------------------------------------------------------------------
// Sample Data
const homies = [
{ name: 'Alex', age: 29, score: 15, id: 1 },
{ name: 'Joe', age: 27, score: 30, id: 2},
{ name: 'Stepan', age: 25, score: 20, id: 3 },
{ name: 'Mark', age: 27, score: 25, id: 4 },
{ name: 'Kam', age: 25, score: 20, id: 5 }
];
// Step 1
// --------------------------------------------------
// Write a function that returns the object with the highest score
// e.g. -> highest(homies) -> {'name: 'Joe' ... }
//
function highestScore(homies) {
return homies.sort((homieA, homieB) => {
return homieB.score - homieA.score;
})[0];
}
console.log(
'by score: expect joe',
highestScore(homies)
)
// Step 2
// -------------------------------------------------
// Write a function that returns the object with the highest value
// based on a given field
// e.g. -> highest(homes, 'age') -> {'name: 'Alex' ... }
function highestScoreField(homies, field) {
return homies.sort((homieA, homieB) => {
return homieB[field] - homieA[field];
})[0];
}
console.log(
'by-age: expect alex',
highestScoreField(homies, 'age')
);
// Step 3
// -------------------------------------------------
// Write a function that returns the object with the highest or lowest value
// based on a given field and a direction ('high', 'low')
// e.g. -> highest(homes, 'score', 'high') -> {'name: 'Joe' ... }
// e.g. -> highest(homes, 'score', 'low') -> {'name: 'Alex' ... }
function highestScoreFieldDir(homies, field, dir) {
return homies.sort((homieA, homieB) => {
const [leftScore, rightScore] =
(dir === 'high')
? [homieB[field], homieA[field]]
: [homieA[field], homieB[field]];
return leftScore - rightScore;
})[0];
}
console.log(
'by-dir:',
'expect joe',
highestScoreFieldDir(homies, 'score', 'high'),
'expect alex',
highestScoreFieldDir(homies, 'score', 'low')
);
// Step 4
// -------------------------------------------------
// Write...