Implement a function to sort an array of objects by a specific key.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
Use the built-in Array.prototype.sort() method with a custom comparison function.
The comparison function takes two arguments (a, b) and should return:
a should come before b.a should come after b.function sortObjectsByKey(arr, key) {
// Using slice() to create a shallow copy to avoid mutating the original array.
return arr.slice().sort((a, b) => {
const valueA = a[key];
const valueB = b[key];
if (valueA < valueB) {
return -1;
}
if (valueA > valueB) {
return 1;
}
return 0;
});
}
const people = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
console.log(sortObjectsByKey(people, 'age'));
// Output: [{ name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Charlie', age: 35 }]