I have an array filled with objects “fruits” which have properties “kind”, “color”. I need to use
quicksort
method to sort given fruits by their colors in accordance to a given order of colors.
For example, an array “fruits” has
{kind: apple, color: red}; {kind: orange, color: orange}; {kind: watermelon, color: green}; {kind: blueberry, color: blue}.
And you need to sort these fruits in accordance to rainbow color orders. How do we do that? All examples, that I have found on the internet only deal with numbers. I know that first step is to make a function which tells us the weight of a color in a given order:
const comparationColor = (fruit1, fruit2) => {
const priority = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'];
const priority1 = priority.indexOf(fruit1.color);
const priority2 = priority.indexOf(fruit2.color);
return priority1 > priority2;
};
And then there is a
quickSort
function:
quickSort (arr) {
if (arr.length < 2) {
return arr;
}
let pivot = arr[0];
let leftArr = [];
let rightArr = [];
for (let i = 1; i < arr.length; i++) {
if (comparation(pivot, arr[i])) {
leftArr.push(arr[i]);
} else {
rightArr.push(arr[i]);
}
}
return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
}
But how do I combine them?
user25296678 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.