How to sort object vector by checking for an attribute?

2

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

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 distance attribute, 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}}
];

In 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 vector by checking attribute distance ?

    
asked by anonymous 26.05.2017 / 22:26

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);
    
26.05.2017 / 22:28
3

Another suggestion is to use lib lodash. It has several javascript functions that do the "hard" work. For example, performing this sort operation would be as simple as this:

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 you 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 you wanted to sort by several fields:

If you 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: link

    
26.05.2017 / 22:59