A Kata On JavaScript’s Arrow Functions.
Problem Statement: You have to sort an array of objects; sort, based on a property of an object using arrow functions in JavaScript.
A great, simple kata problem to learn more about sorting arrays of objects, and implementing arrow functions in JavaScript.
Test Cases & Kata.
JavaScript Kata: Sorting an array of objects, using arrow function(s).
Here’s how I solved it
var OrderPeople = function(people){
return people.sort( (p, p2) => {return p.age - p2.age; });
}
//calling the function with an array of objects
OrderPeople([ { age: 83, name: 'joel' },
{ age: 46, name: 'roger' },
{ age: 99, name: 'vinny' },
{ age: 26, name: 'don' },
{ age: 74, name: 'brendan' } ]);
The Most Precise And/Or Elegant Solution(s)
This one’s by DJTButm_source=indefiniteloop.com){:target=”_blank” title=”Sorting an array of objects, using arrow function(s) - kata”} (and over 100+ other people).
var OrderPeople = function(people){
return people.sort((a,b) => a.age - b.age );
}
Here’s another interesting solution by cave.on
const OrderPeople = people => people.sort((a,b) => a.age-b.age)
Arrow Functions
Always anonymous functions, arrow functions have a shorter syntax as compared to the regular function definition, and declaration. Arrow functions can be used with the keyword “this”. Read more about Arrow Functions in JavaScript.