Sorting Array Data by Value in JavaScript
Managing and manipulating array data is a common task in web development. How to sort an array of objects based on a specific value using JavaScript. The example used will be sorting a list of objects based on the order
property.
1. Initial Data
Let’s start with a set of data which is an array of objects. Each object has two properties: name
and order
.
let data = [
{ name: 'Edward', order: 21 },
{ name: 'Sharpe', order: 37 },
{ name: 'And', order: 45 },
{ name: 'The', order: -12 },
{ name: 'Magnetic', order: 13 },
{ name: 'Zeros', order: 37 }
]
In the example above, we have six objects with various order
values. Our goal is to sort these objects based on the order
value.
2. Using sort()
to Sort the Array
JavaScript provides the sort()
method which allows us to sort the elements of an array. This method takes a compare function as an argument that determines the order of sorting.
Basic syntax for sort()
:
array.sort((a, b) => {
// sorting code
})
The compare function takes two arguments, a
and b
, which are two elements of the array being compared. Based on the returned value, the elements will be sorted:
- If the result of
b - a
is positive,b
will be placed beforea
. - If the result of
b - a
is negative,a
will be placed beforeb
. - If the result is zero, the order between
a
andb
remains unchanged.
3. Sorting Implementation
To sort the array of data based on the order
value in descending order, you can use the following code:
let result = data.sort((a, b) => {
return b.order - a.order
})
Here, subtracting b.order
from a.order
will sort the array such that the objects with the highest order
value will be first.
4. Sorted Result
After sorting, here is the result of the data
array:
console.log(result);
Output:
[
{ name: 'And', order: 45 },
{ name: 'Sharpe', order: 37 },
{ name: 'Zeros', order: 37 },
{ name: 'Edward', order: 21 },
{ name: 'Magnetic', order: 13 },
{ name: 'The', order: -12 }
]
As you can see, the objects in the array are now sorted based on the order
value from highest to lowest.
5. Adjusting the Order
If you want to sort the data in ascending order, you only need to reverse the subtraction:
let result = data.sort((a, b) => {
return a.order - b.order
})
This will sort the objects in the array from smallest to largest based on the order
value.
6. Conclusion
Using the sort()
method in JavaScript provides an easy and flexible way to sort array data, especially when working with arrays of objects. By understanding how the compare function works, you can easily adjust the sorting to meet your needs. This is a very useful technique in application development, especially when you need to display data in a specific order.