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?
CodePudding user response:
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)
CodePudding user response:
this.array.sort((a, b) => a['time'] - b['time']);
CodePudding user response:
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