Here, I have to create a function which has 2 parameters, array of employee and attribute which returns all employees sorted based on the employees attribute being passed as second parameter.
function compare(arr, name){
}
let arr = [
{name :"om", age:45},
{name :"guru", age:95},
{name :"subh", age:25},
{name :"rahul", age:22},
{name :"raju", age:35},
];
//// output should be array either sorted by name or age
CodePudding user response:
The javascript built-in array sort()
function has an parameter to pass in your own compare function. The sort()
function will compare 2 different values in the array and determine the position of them based on a call to the compare function with 2 parameters: a
and b
. By passing in a compare function, you can specify exactly what properties of the objects you want to compare. In your case, what you could use is
function compare(arr, name){
return arr.sort((a, b) => a[name] - b[name]);
}
let arr = [
{name :"om", age:45},
{name :"guru", age:95},
{name :"subh", age:25},
{name :"rahul", age:22},
{name :"raju", age:35},
];
Link to more information about the sort()
function
CodePudding user response:
You could take a function which works for numbers as well as for strings.
function sort(array, key) {
return array.sort((a, b) => (a[key] > b[key]) - (a[key] < b[key]));
}
const
data = [{ name: "om", age: 45 }, { name: "guru", age: 95 }, { name: "subh", age: 25 }, { name: "rahul", age: 22 }, { name: "raju", age: 35 }];
console.log(sort(data, 'name'));
console.log(sort(data, 'age'));
.as-console-wrapper { max-height: 100% !important; top: 0; }