function sortedPeopleArray(peopleArray) {
arrayCopy = [...peopleArray];
function compare(a, b) {
const nameA = a.name.toUpperCase();
const nameB = b.name.toUpperCase();
let comp = 0;
if (nameA > nameB) {
comp = 1;
} else if (nameA < nameB) {
comp = -1;
}
return comp;
}
arrayCopy.sort(compare);
arrayCopy.sort(function(a,b) {
return (a.satisfaction - b.satisfaction) * -1;
});
arrayCopy.sort(function(a,b) {
return (a.rating - b.rating) * -1;
});
arrayCopy.sort(function(a,b) {
return (a.age - b.age) * -1;
});
return arrayCopy;
}
I have attempted to sort an array based on all of its property values but my function does not return the desired output. Is there a better way to approach this?
How would I sort an array of objects (code below) in descending order of:
- age (highest to lowest)
- rating (highest to lowest)
- satisfaction (highest to lowest)
- name (by alphabetical order)
These properties are considered exactly in that order when sorting
If two values are equal, then the next property on the list is looked at to determine which person is placed first. eg. if two people have the same rating then the person with a higher satisfaction number is placed first
const array = [
{
name: A
age: 22
rating: 5
satisfaction: 2
},
{
name: B
age: 25
rating: 7
satisfaction: 4
},
{
name: C
age: 22
rating: 9
satisfaction: 8
},
];
The outputted array should be
result = [
{ name: B,
age: 25,
rating: 7,
satisfaction: 4,
},
{ name: C
age: 22
rating: 9
satisfaction: 8
},
{ name: A
age: 22
rating: 5
satisfaction: 2
},
];
CodePudding user response:
You need to apply the comparisons one after another, linked by the "or" (||
) operator. The or operator will not process its second argument if the first one was found to be truthy, i. e. if it returned a value different from 0.
Comparing numbers is easiest accomplished by a simple subtraction. Strings can be compared with String.prototype.localeCompare()
:
const arr = [{name: "A",age: 22,rating: 5,satisfaction: 2},{name: "B",age: 25,rating: 7,satisfaction: 4},{name: "C",age: 22,rating: 9,satisfaction: 8}];
arr.sort((a,b)=>
b.age-a.age ||
b.rating-a.rating ||
b.satisfaction-a.satisfaction ||
b.name.localeCompare(a.name))
console.log(arr);
CodePudding user response:
Do the comparison all in one function.
function compare(oA, oB)
{
if(oA.age == oB.age)
{
if(oA.rating == oB.rating)
{
if(oA.satisfaction == oB.satisfaction)
{
const nameA = oA.name.toUpperCase();
const nameB = oB.name.toUpperCase();
let comp = 0;
if (nameA > nameB) {
comp = 1;
} else if (nameA < nameB) {
comp = -1;
}
return comp;
}
else
{
return oB.satisfaction - oA.satisfaction;
}
}
else
{
return oB.rating - oA.rating;
}
}
else
{
return oB.age - oA.age;
}
}
const array = [
{
name: 'A',
age: 22,
rating: 5,
satisfaction: 2
},
{
name: 'B',
age: 25,
rating: 7,
satisfaction: 4
},
{
name: 'C',
age: 22,
rating: 9,
satisfaction: 8
},
];
let arrayCopy = [...array];
arrayCopy.sort(compare);
console.log(arrayCopy)