Sort array of object in javascript
Problem: sort array of objects by a property
Example:
const array = [
{ id: 1, name: "tung" },
{ id: 3, name: "nguyen" },
{ id: 2, name: "thanh" }
]
Solution:
// Sort list array by id
const sortedArray = array.sort((item1, item2) => item1.id - item2.id)
Explain:
Array in javascript has a sort
method to sort.
sort
method have input is a compare function with two items and output is:
- a positive number means item1 will place before item2
- a negative number means item1 will place after item2
- a zero number mean no change in the order of items