The following is the function to sort an array of objects by some property.

function createCompareFunc(propertyName){ 
  return function(obj1, obj2){    
    var val1=obj1[propertyName];   
    var val2=obj1[propertyName];
    return val1-val2;    
  }
}

var data=[{name:'a', age:12},{name:'b',age:5}];    
console.log(typeof data[0]['age']); //number    
console.log(data.sort(createCompareFunc('name')));    
//[Object{name="a", age=12},Object{name="b",age=5}]   
console.log(data.sort(createCompareFunc('age')));     
//[Object{name="a", age=12},Object{name="b",age=5}], but I want to get '[Object{name="b",age=5},Object{name="a", age=12}]'

What's wrong with number?

share|improve this question
3  
In the compare function, is val2=obj1[propertyName] a typo, or is it actually in your code? – mgibsonbr Aug 11 at 8:04
feedback

2 Answers

Typo obj1 instead of obj2 in line 6.

share|improve this answer
feedback

Here is the code and its' working for what you asked :

function createCompareFunc(propertyName){
  return function(obj1, obj2){ 
     val1=obj1[propertyName];   
     val2=obj2[propertyName];    
    return val1-val2;    
  }
}

var data=[{name:'a', age:12},{name:'b',age:5}];    
console.log(typeof data[0]['age']); 
console.log(data.sort(createCompareFunc('age'))); 
console.log(typeof data[0]['name']);
console.log(data.sort(createCompareFunc('name')));

there is a logical error, i think you havn't noticed it. You can not compare string with - operator in javascript, so pass the type of property as arguments to createCompareFunc(propertyName,type), and based on that sort it. eg:

createCompareFunc(propertyName,type)
{
//function
//sorting based on type of element
}
createCompareFunc('age',typeof data[0]['age']); 
share|improve this answer
You have to check this : natural sort of text and numbers, JavaScript – bios Aug 11 at 10:38
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.