乐闻世界logo
搜索文章和话题

How to sort array of objects by string property value

3个答案

1
2
3

In JavaScript, to sort an array of objects based on the string properties of the objects, you can use the Array.prototype.sort() method. This is a custom sorting approach that determines the array's order based on the return value.

Here are the specific steps and examples for sorting an array based on string properties of objects:

  1. Define a comparison function that takes two parameters, representing the objects to compare.
  2. Within the comparison function, compare the objects based on their string properties.
  3. Use the localeCompare method of strings for case-insensitive sorting, or use the < and > operators for case-sensitive sorting.
  4. Call the sort method of the array and pass the comparison function as an argument.

Here is an example where we have an array of student objects and want to sort the array based on the students' names (the name property).

javascript
// Array of student objects let students = [ { id: 1, name: "张三" }, { id: 2, name: "李四" }, { id: 3, name: "王五" } ]; // Comparison function function compareByName(a, b) { // Use localeCompare for case-insensitive string comparison return a.name.localeCompare(b.name); } // Sort by name students.sort(compareByName); // Output the sorted array console.log(students);

If case-sensitive sorting is required:

javascript
function compareByNameCaseSensitive(a, b) { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; } students.sort(compareByNameCaseSensitive);

The above code sorts the students array based on the lexicographical order of the students' names. For other sorting methods (e.g., reverse order or sorting based on other properties), simply adjust the logic of the comparison function compareByName.

2024年6月29日 12:07 回复

I couldn't find any mention of the OR operator in the TypeORM documentation or source code. Is it fully supported?

I'm trying to perform a basic search using the repository.

js
db.getRepository(MyModel).find({ name : "john", lastName: "doe" })

I know this generates an AND operation, but I need an OR operation, so the SQL would be: name='john' OR lastName='doe'

Am I forced to use the query builder to perform such a basic operation?

2024年6月29日 12:07 回复

In ES6/ES2015 or later versions, you can do this:

javascript
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));

Before ES6/ES2015

javascript
objs.sort(function(a, b) { return a.last_nom.localeCompare(b.last_nom) });
2024年6月29日 12:07 回复

你的答案