Sorting the data array is working fine for me, but now I want to pass values as parameters. However, if the user enters a 'parameter' that doesn't exist, I need to display an error message using TRY/CATCH. Can someone please help me understand why it's not working?
const data = [
{
"color": "Blue",
"door": 3,
"wheel": 3,
"year": 2005,
"brand": "GMC",
"sold": false,
"owner": "Chalmers Boobyer",
"motor": 1.7,
"assembled": "09/08/2022"
},
{
"color": "Indigo",
"door": 4,
"wheel": 4,
"year": 1996,
"brand": "Lincoln",
"sold": true,
"owner": "Morten Coffin",
"motor": 1.7,
"assembled": "26/08/2021"
}
];
function bubbleSort(arr, ord, prop){
try{
if(ord === 'asc'){
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr.length - 1 - i; j++){
if(arr[j][prop] > arr[j+1][prop]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
} else if(ord === 'desc'){
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr.length - 1 - i; j++){
if(arr[j][prop] < arr[j+1][prop]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
return (arr);
} catch(err){
console.log(err);
}
}
console.log(bubbleSort(data, 'asc', 'wheel'));