Home  >  Article  >  Web Front-end  >  JavaScript object array sorted in descending order by a certain property

JavaScript object array sorted in descending order by a certain property

巴扎黑
巴扎黑Original
2016-12-06 10:08:331569browse

<!DOCTYPE html> 
<html> 
<body> 
<script> 
//定义一个对象数组 
var data = [{ 
name: "海外事业部", 
value: 0.58 
}, { 
name: "内销", 
value: 0.36 
}, { 
name: "互联网中心", 
value: 0.78 
}];    
//定义一个比较器--降序排列 
function compare(propertyName) { 
return function(object1, object2) { 
var value1 = object1[propertyName]; 
var value2 = object2[propertyName]; 
if(value2 < value1) { 
return -1; 
} else if(value2 > value1) { 
return 1; 
} else { 
return 0; 
} 
} 
} 
console.info(JSON.stringify(data)); 
//使用方法 
data.sort(compare("value"));  
console.info(JSON.stringify(data));  
</script> 

<h1>JavaScript 对象数组 按照某个属性 降序排列</h1> 

<p> 
JavaScript 对象数组 按照某个属性 降序排列 
</p> 



</body> 

</html>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn