I need to sort an multidimentional array with Non-ASCII characters and multiple objects.
tried this but doesn't worked
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'á', age: 40 },
{ name: 'b', age: 36 }
]
const nameLocale = users.sort((a, b) => (a.name.localeCompare(b.name)));
const sortedUsers = _.orderBy(users, [nameLocale, 'age'], ['asc', 'asc'])
the sorted array i need would be like this:
{ name: 'á', age: 40 }
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 36 }
but the responde i got is this:
[
{ name: 'B', age: 34 },
{ name: 'b', age: 36 },
{ name: 'á', age: 40 },
{ name: 'A', age: 48 }
]
CodePudding user response:
You can remove diacritics with the following code, from: https://www.davidbcalhoun.com/2019/matching-accented-strings-in-javascript/
Then it seems like you consider uppercase and lowercase letters equal, so you can convert to lowercase.
Also, orderBy
takes a function as a parameter, not a sorted array.
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'á', age: 40 },
{ name: 'b', age: 36 }
]
const sortByName = (user) => user.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLocaleLowerCase();
const sortedUsers = _.orderBy(users, [sortByName, 'age'], ['asc', 'asc']);
console.log(sortedUsers);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>