Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort an array of objects based on numeric key

Tags:

javascript

I have an array of objects that looks like this:

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 }
]

How could I sort it for use in a for loop like this.

for(var i in data) {

}

I tried:

for(var i in data | orderBy:'position')

But that is angular so normal Javascript it doesn't work.

I'm thinking their must be some way to sort the array before looping through it, or adding a filter to the loop, not sure which is the best way.

like image 715
Jordash Avatar asked Jul 19 '18 01:07

Jordash


2 Answers

But that is angular so normal Javascript it doesn't work.

Simply you can use JavaScript sort function. It will work in Angular(TypeScript) also.

Note: When sorting numbers, you can simply use the compact comparison:

myArray.sort((n1,n2) => n1 - n2);

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 }
];

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

console.log(data);
like image 95
NullPointer Avatar answered Oct 17 '22 20:10

NullPointer


Use Array.prototype.sort (doc) and pass the compare function as you want:

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 },
 // add for actually seeing the correct result
 {
   title: 'Cake',
   position: 2,
 }
];

function compareFunction(a,b){
  if(a.position > b.position)
    return 1;
  else
    return -1;
}

data.sort(compareFunction);

console.log(data);
like image 2
Terry Wei Avatar answered Oct 17 '22 21:10

Terry Wei