I have - array of objects - list items, I sort these items by fieldName
. Normally it seems it works fine, but on some items it behaves strange and doesn't sort items properly.
Here is the code that I am making sorting:
elements.slice(0).sort((a, b) => {
if (a[fieldName] === '' || a[fieldName] == null) return 1;
if (b[fieldName] === '' || b[fieldName] == null) return -1;
return (
itemSort
? a[fieldName]?.toLowerCase() < b[fieldName]?.toLowerCase()
: a[fieldName]?.toLowerCase() > b[fieldName]?.toLowerCase()
)
? 1
: -1;
})
itemSort
is a boolean and I decide to make A-Z
or Z-A
sorting.
Here is a picture from strange behaviour, I only see the wrong sorting on these items.
Here is an example of elements
[
{
icon: "IssueTracking"
id: "62a0868c2b2b180061ab05d8"
name: "[DEMO ASLC] All Issues"
type: "sheet"
updatedAt: "2022-12-05T15:17:23.072Z"
url: "/admin/documents/edit/62a0868c2b2b180061ab05d8"
},
{
icon: "..."
id: "..."
name: "..."
type: "..."
updatedAt: "..."
url: "..."
},
...
]
CodePudding user response:
.sort()
method modifies array itself, so you need to copy the array into a new array if you would like to keep your original array order in place.
const elementArray = [
{ name: "abc" },
{ name: "abb" },
{ name: "cc" },
{ name: "1bb" },
{ name: "4bc" },
{ name: "abb4" },
{ name: "" },
];
const sortItems = (elements, asc = true) => {
const sortedArray = [...elements];
sortedArray.sort((a, b) => {
let sortResult = a.name?.toLowerCase() > b.name?.toLowerCase() ? 1 : -1;
return asc ? sortResult : sortResult * -1
});
return sortedArray;
};
console.log(`descending: ${JSON.stringify(sortItems(elementArray, false))}`);
console.log(`ascending: ${JSON.stringify(sortItems(elementArray))}`);
CodePudding user response:
One of the best way to do this is to use the Lodash sortBy method.
You can install this library with npm or yarn and simply do _.sortBy(elements, 'fieldName')