JavaScript Day 42 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation
100 Days of JavaScript Interview Prep: A Beginner’s Journey

Question 1 — How to sort an array of objects based on a car age ?
const cars = [
{ name: 'i10', age: 10 },
{ name: 'magna', age: 25 },
{ name: 'ford', age: 35 },
];Answer -
First Solution
[...cars].sort((a,b)=>{
return a.age - b.age ;
})
console.log(cars)Second Solution
function compareAge(a, b) {
return a.age - b.age;
}
// Sort the array based on age
cars.sort(compareAge);
console.log(cars);Question 2 — How to sort an array of objects based to dynamic key?
const cars = [
{ make: 'Toyota', model: 'Corolla', year: 2018 },
{ make: 'Honda', model: 'Civic', year: 2019 },
{ make: 'Ford', model: 'Focus', year: 2017 },
];Answer
Step 1 — Create the custom function
Step 2 — Access the dynamic key with array.sort
a[key]andb[key]access the values of the objects based on the dynamic key
Step 3 — Use the compare condition and return
Step 4 — Use sortByKey method
sortByKeyfunction takes an array of objects and a dynamic key as parameters.
// Function to sort array of objects based on dynamic key
function sortByKey(array, key) {
return array.sort((a, b) => {
// Access the values of the objects using the dynamic key
const valueA = a[key];
const valueB = b[key];
// Compare the values
if (valueA < valueB) return -1;
if (valueA > valueB) return 1;
return 0;
});
}
// Sort cars array based on the 'year' key
const sortedCarsByModel = sortByKey(cars, 'model');
console.log(sortedCarsByModel);Happy Coding and Stay Tuned :)
Kind is always cool !!!
Share knowledge to gain knowledge !!!!
Be kind and treat people with respect !!
If you find my blog helpful, then please subscribe, claps and follow to support :)







