I couldn't find the answer for this on Stack Overflow.
I have a function called quickSort:
function quickSort(array, prop) {
if (array.length <= 1) return array;
const pivot = array[0]; // I've tried array[0][prop] but it doesn't work
const left = [];
const right = [];
for (let i = 1; i < array.length; i++) {
if (array[i][prop] < pivot) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(quickSort(data, 'motor'));
And I want sort this array of objects by motor:
let data = [
{
"color": "A",
"door": 1,
"wheel": 3,
"year": 1963,
"brand": "GMC",
"sold": false,
"owner": "Chalmers Boobyer",
"motor": 2.6,
"assembled": "20/08/2021"
},
{
"color": "B",
"door": 2,
"wheel": 2,
"year": 1980,
"brand": "Ford",
"sold": false,
"owner": "Angelia Cromett",
"motor": 2.5,
"assembled": "02/05/2021"
},
{
"color": "C",
"door": 3,
"wheel": 1,
"year": 1999,
"brand": "Audi",
"sold": false,
"owner": "Barth Pickring",
"motor": 2.0,
"assembled": "15/02/2021"
},
{
"color": "D",
"door": 4,
"wheel": 1,
"year": 2008,
"brand": "Hyundai",
"sold": true,
"owner": "Aurore Soaper",
"motor": 1.2,
"assembled": "02/01/2019"
}
];
Can someone explain how I can make array[0][prop] work?
pivotis an object, so you need to extract propertyarray[i][prop] < pivot[prop]to comparepropin this linereturn [...quickSort(left), pivot, ...quickSort(right)];