1

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?

1
  • 3
    In the compare function, is val2=obj1[propertyName] a typo, or is it actually in your code? Commented Aug 11, 2012 at 8:04

2 Answers 2

0

Typo obj1 instead of obj2 in line 6.

0

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']); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.