-1

I have some data which I need to sort using the first column of each object.

The project uses Angular / Typescript but it's still JS.

Here's how the data looks:

[
    {
        time: 1000.189,
        other: 100 
    },
    {
        time: 1023.189 ,
        other: 105 
    },
    {
        time: 999.189,
        other: 100  
    }
]

So the above should look like this:

[
    {
        time: 999.189,
        other: 100  
    },
    {
        time: 1000.189,
        other: 100 
    },
    {
        time: 1023.189,
        other: "105 
    }
]

How can I do this?

  • These objects don't have columns. There is no first column. – jarmod Nov 04 '22 at 15:29
  • 1
    Does this answer your question? [Sorting arrays numerically by object property value](https://stackoverflow.com/questions/7889006/sorting-arrays-numerically-by-object-property-value) – Emiel Zuurbier Nov 04 '22 at 15:32

3 Answers3

1

function sortByColumn(colname){
  return array.sort((a,b)=>a[colname]-b[colname])
  }

const array = [
    {
        time: 1000.189,
        other: 100 
    },
    {
        time: 1023.189 ,
        other: 105 
    },
    {
        time: 999.189,
        other: 100  
    }
]

const orderSorted = sortByColumn('order')
const timeSorted = sortByColumn('time')

console.log(orderSorted)

console.log(timeSorted)
Shreyansh Gupta
  • 382
  • 1
  • 10
0
this.array.sort((a, b) => a['time'] - b['time']);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Randy
  • 56
  • 3
0
const array = [
  {
    time: 1000.189,
    other: 100
  },
  {
    time: 1023.189 ,
    other: 105
  },
  {
    time: 999.189,
    other: 100
  }
]

const result = array.sort((a, b) => a.time - b.time);

console.log(result);

result = [ { time: 999.189, other: 100 }, { time: 1000.189, other: 100 }, { time: 1023.189 , other: 105 }, ]

this works in Angular/Javascript

LocoBE
  • 16
  • 1