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

JavaScript object array sorted in descending order by a certain property

巴扎黑
Release: 2016-12-06 10:08:33
Original
1618 people have browsed it

<!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>
Copy after login


Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template