How to sort object vectors by checking an attribute?

Asked

Viewed 60 times

2

I can sort a simple list using the method sort Behold:

var distances = [15, 18, 27, 29, 5, 3]

distances.sort(function(a, b){
   return a-b;
});

console.log(distances);

But I would like to sort a list of objects based on the attribute distance, for example:

var listDistances = [
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}}
];

This way the result would be:

var listDistances = [        
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}},
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
];

How to sort object array by checking the attribute distance?

2 answers

5


It’s the same thing

var listDistances = [
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}}
];


listDistances.sort(function(a, b){
   return a.distance - b.distance;
});

console.log(listDistances);

  • Jesus, I think I’d done something wrong then! Vlw... now it’s gone! =)

3

Another suggestion is to use lib lodash. It has several javascript functions that make the job "hard". For example, performing this ordering operation would be so simple:

var listDistances = [
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}}
];

_.sortBy(listDistances, ['distance']);

If I wanted to sort by a sub-item:

var listDistances = [
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}}
];

_.sortBy(listDistances, ['location.lat']);

If I wanted to order through several camps:

If I wanted to sort by a sub-item:

var listDistances = [
    {distance: 857, location: {lat: 15.246, lnt:16.4552}}, 
    {distance: 26, location: {lat: 18.246, lnt:16.4552}},
    {distance: 740, location: {lat: 15.246, lnt:16.4552}}
];

_.sortBy(listDistances, ['distance', 'location.lat']);

Very simple. The lib link: https://lodash.com/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.