Home > Web Front-end > JS Tutorial > js array sorting

js array sorting

巴扎黑
Release: 2016-11-25 15:07:24
Original
1175 people have browsed it

1. Sorting of arrays. Array sorting can generally be solved using the sort() method.

var id=['001','010','005','006'];
id.sort();
console.log(JSON.stringify(id));//["001","005","006","010"]
Copy after login

But there are many complex arrays that cannot be sorted directly in this way. However, we can sort by modifying the sort() method.

var goods_info=[
        {barcode:"005", type: '食品', name: '方便面', price: '4.5', unit: '袋'},
        {barcode:"000", type: '饮料', name: '可口可乐', price: '3', unit: '瓶'},
        {barcode:"002", type: '水果', name: '苹果', price: '5.5', unit: '斤'},
        {barcode:"001", type: '饮料', name: '雪碧', price: '3', unit: '瓶'},
        {barcode:"004", type: '生活用品', name: '电池', price: '2', unit: '个'},
        {barcode:"003", type: '水果', name: '荔枝', price: '15', unit: '斤'},];
goods_info.sort(function(a,b){
return a.barcode>b.barcode ? 1 : -1;
});
console.log(JSON.stringify(goods_info));
Copy after login

Just like this example, you can sort.

Related labels:
js
source:php.cn
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