Sort()排序,对象的排序
如果我现在需要对JavaScript对象进行排序:
var list = { "you": 100, "me": 75, "foo": 116, "bar": 15 };
想要得到的结果时:
1 list = { 2 "bar": 15, 3 "me": 75, 4 "you": 100, 5 "foo": 116 6 };
第一种是根据obj的values进行排序,返回对象的keys:
var obj={ "a":4, "b":6, "v":9, "e":10 } function SortObj(obj){ return Object.keys(obj).sort((a,b)=>obj[a]-obj[b]) } console.log(SortObj(obj))//["a", "b", "v", "e"]
第二种,JavaScript有sort()函数,需要现在以某种方式获取键的数组并对他们进行排序,使用js的sort()和reduce()函数
var obj={ "a":4, "b":6, "v":9, "e":10 } // function SortObj(obj){ // return Object.keys(obj).sort((a,b)=>obj[a]-obj[b]) // } function SortObj (obj){ return Object.keys(obj).sort().reduce(function(a,v){ a[v]=obj[v]; return a; },{}) } console.log(SortObj(obj))//{a: 4, b: 6, e: 10, v: 9}
第三种,
var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic' }, { name: 'Zeros', value: 37 } ]; console.log(items.sort(function(a,b){ return a.value-b.value//(6) [{…}, {…}, {…}, {…}, {…}, {…}]0: {name: "The", value: -12}1: {name: "Edward", value: 21}2: {name: "Sharpe", value: 37}...