In TypeScript, you can use the Array.prototype.sort() method to sort an array of objects by a property value. The sort() method takes a comparator function as its argument, which should return a negative, zero, or positive value depending on the order in which the elements should be sorted.
Here's an example of how you can use the sort() method to sort an array of objects by a property called "name":
interface Person {
name: string;
age: number;
}
let people: Person[] = [
{ name: "Uzeyr", age: 33 },
{ name: "Ozcan", age: 28 },
{ name: "Ali", age: 30 }
];
people.sort((a, b) => {
if (a.age < b.age) {
return -1;
}
if (a.age > b.age) {
return 1;
}
return 0;
});
console.log(people);
// Output: [{ name: "Ozcan", age: 28 }, { name: "Ali", age: 30 }, { name: "uzeyr", age: 33 }]
In the example above, we defined an interface Person to represent the objects in the array, and created an array of objects that implement the Person interface. We then called the sort() method on the people array and passed in a comparator function that compares the "name" property of two objects and returns a negative, zero, or positive value depending on their relative order. The sort() method then sorts the array in place based on the values returned by the comparator function.
You can use the same approach to sort an array of objects by any property. Just replace "name" with the name of the property you want to sort by, and adjust the comparator function accordingly.
It's important to notice that the sort() method sorts the array in place, meaning it modifies the original array and doesn't create a new one.
Top comments (0)