-1
array: [
  {
    distance: "4 km",
    name: "A",
    AmountDue: 58576,
    OrderValue: 0,
    Visited: "",
  },
  {
    distance: "10.3 km",
    name: "B",
    AmountDue: 58576,
    OrderValue: 0,
    Visited: "",
  },
  {
    distance: "8 km",
    name: "C",
    AmountDue: 58576,
    OrderValue: 0,
    Visited: "",
  }
]

How to sort the above array in ascending order based on distance field. Please help. I am stuck in this

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Ankit Kumar
  • 118
  • 12

7 Answers7

3

You could get the distance as numerical value and sort by the delta of it.

const
    getDistance = string => 
        (([number, unit]) => number * { km: 1000, m: 1 }[unit])
        (string.split(' '));

var data = [{ distance: "4 km", name: 'A', AmountDue: 58576, OrderValue: 0, Visited: "" }, { distance: "10.3 km", name: 'B', AmountDue: 58576, OrderValue: 0, Visited: "" }, { distance: "8 km", name: 'C', AmountDue: 58576, OrderValue: 0, Visited: "" }, { distance: "2 m", name: 'A', AmountDue: 58576, OrderValue: 0, Visited: "" }];

data.sort((a, b) => getDistance(a.distance) - getDistance(b.distance));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Use method sort() and try something like this:

function compare( a, b ) {
      if ( a.distance < b.distance ){
        return -1;
      }
      if ( a.distance > b.distance ){
        return 1;
      }
      return 0;
    }

array.sort( compare );
Fotiou D.
  • 431
  • 6
  • 11
0

You need to replace the character part with empty string, convert it to Number and then use the sort function.

In a nutshell,

array.sort((a, b) => Number(a.distance.replace('km','')) > Number(b.distance.replace('km','')) ? 1 : -1)
Mahbub Moon
  • 491
  • 2
  • 8
0

If possible you could convert the distance to a number on the server. Otherwise use parseFloat(). It will ignore the 'km' part.

When other units come into play you will have to parse it with regex and convert to a single unit. Meters for example.

Tom Dezentje
  • 631
  • 3
  • 16
0

You should use the sort() method. Try like this.

array.sort((a,b)=> {return a.distance.split(' ')[0] - b.distance.split(' ')[0] });
akpgp
  • 761
  • 6
  • 10
0

See you are here trying to sort distance (probably ascending order). But distance is of type string thus making it difficult to sort.

One approach is to make a change in your API and make the distance as a integer type. Best will be to convert the distance into meters instead of kilometers.

Now solving your question.

1) There is an error in your objects. There should be a , after distance: "4 km" and distance: "10.3 km" and distance: "8 km"

2) We can user sort() to sort based on distance.

userArr.sort((a,b)=> {return a.distance.split(' ')[0] - b.distance.split(' ')[0] });

where userArr is your array of objects.

3) Since distance is in string format, we need to extract the numeric part from the string. We can user split().

For reference read this answer https://stackoverflow.com/a/42815997/11926970

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
0

As far as i know you can't really sort an object. However, you can log all of your existing distances and then based on distance count, filter the array in a for loop. In order to avoid logging the same distance if you have the same distance in 2 objects you'd need a unique identificator on each set (like the name) to identify it by and remove it from the array, I've added such a process in my example which is why i added object D.

When using multiple distances you can detect this via string.includes("km") and just multiply distances that contain the trigger "km". Which means you'd have to parse the numbers first since you supply them as string.

let my = {
    array: [
    {
        distance: "4 km",
        name: 'A',
        AmountDue: 58576,
        OrderValue: 0,
        Visited: ""
    },
    {
        distance: "10.3 km",
        name: 'B',
        AmountDue: 58576,
        OrderValue: 0,
        Visited: ""
    },
    {
        distance: "8 km",
        name: 'C',
        AmountDue: 58576,
        OrderValue: 0,
        Visited: ""
    },
    {
        distance: "8 km",
        name: 'D',
        AmountDue: 12346,
        OrderValue: 0,
        Visited: ""
    }]
}
console.log(my.array)
sorter(my)

function sorter(my)
{
    array = my.array;
    distances = []
    for (i = 0; i < array.length; i++)
    {
        distances.push(array[i].distance.split(" ")[0])
    }
    distances.sort(function(a, b)
    {
        return a - b
    });
    newarray = []
    for (i = 0; i < distances.length; i++)
    {
        newarray.push(array.filter(e => e.distance.split(" ")[0] == distances[i])[0])
        array = array.filter(f => f.name != array.filter(e => e.distance.split(" ")[0] == distances[i])[0].name)
    }
    console.log(newarray)
}