如何通过时间戳反向排序javascript对象

时间:2017-11-08 04:27:22

标签: javascript arrays sorting ecmascript-6 maps

我似乎无法通过时间戳正确地对Javascript对象进行反向排序。我从这篇SO here帖子中得到了这个帖子:here

问题:

1) object is already sorted on console log for some reason 
2) sorting seems to have had no effect 

代码:

var map = {1505932515: "some item", 1505932695: "some item", 1505832202: "some item", 1508425777: "some item", 1508872138: "some item", 1509022385: "some item", 1509034662: "some item"}
console.log(map); // Why is this already sorted anyway

var sortedMap = {};
Object.keys(map).sort().reverse().forEach(function(key) {
sortedMap[key] = map[key];
});
console.log(sortedMap);

实时测试:JS Bin

这是在Google Chrome上进行的测试。

3 个答案:

答案 0 :(得分:1)

您的sort功能,正如您所做的那样,正在排序strings,您需要将其转换为数字。然后正如PHPGlue所提到的,你的对象并不关心插入顺序,它只会执行本机实现所说的应该做的事情。因此,如果按降序插入,则可能无法获得降序。但是,Map确实尊重订单。你可以这样做:



var map = {1505932515: "some item", 1505932695: "some item", 1505832202: "some item", 1508425777: "some item", 1508872138: "some item", 1509022385: "some item", 1509034662: "some item"};

var map = Object.keys(map).sort(function(a,b){ return +b - +a;}).reduce(function(t,k) {
    t.set(k,map[k]);
    return t;
},new Map());

map.forEach(function(v,k) {
 console.log(k,v);
});




+函数中的sort运算符是将字符串转换为数字的简便方法。

答案 1 :(得分:1)

def maximumeven(st):
    largest = - 3
    for i in st:
        if i in '02468' and int(i) >largest:
            largest = int(i) 
        if largest == 8:
            break
    return largest

答案 2 :(得分:-1)

阅读我的评论。这就是我要做的事情:

//<![CDATA[
/* external.js */
var doc, bod, E, old = onload; // for reuse onload
onload = function(){
if(old)old(); // change var name if using technique on other pages
doc = document; bod = doc.body;
E = function(id){
  return doc.getElementById(id);
}
var map = {1505932515:'was first', 1505932695:'was second', 1505832202:'was third', 1508425777:'was fourth', 1508872138:'was fifth', 1509022385:'was sixth', 1509034662:'was seventh'};
var out = E('out'), keysInOrder = [];
for(var i in map){
  keysInOrder.push(+i);
}
keysInOrder.sort(function(a, b){
  return a-b;
});
for(var i=0,k,l=keysInOrder.length; i<l; i++){
  k = keysInOrder[i]; out.innerHTML += k+' : '+map[k]+'<br />';
}
}
//]]>
/* external.css */
html,body{
  padding:0; margin:0; background:#000;
}
.main{
  width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width' />
    <title>Sort an Object by Numeric Keys</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
  <body>
    <div class='main'>
      <div id='out'></div>
    </div>
  </body>
</html>