JS:按最近的时间戳排序

时间:2021-07-29 11:28:40

标签: javascript

我需要按与当前时间戳最近的时间戳对数组进行排序,但排序错误。这怎么办?

console.log(new Date(1627569000000));
console.log(new Date(1627565400000));
console.log(new Date(1627561800000));
console.log(new Date(1627572600000));


const arr = [{
  from: 1627569000000
}, {
  from: 1627565400000
}, {
  from: 1627561800000
}, {
  from: 1627572600000
}];

const now = 1627557449263;


const [res] = arr.sort(item => item.from - now);


console.log(new Date(res.from))

3 个答案:

答案 0 :(得分:0)

这可能对你有帮助

"visible": {
 "BOOL": true
},
"active": {
 "BOOL": true
},
"handles": {
"M": {
    "end": {
        "M": {
            "active": {
                "BOOL": false
            },
            "highlight": {
                "BOOL": true
            },
            "moving": {
                "BOOL": false
            },
            "x": {
                "N": "2487"
            },
            "y": {
                "N": "2555"
            }
        }
    },
    "initialRotation": {
        "N": "0"
    },
    "start": {
        "M": {
            "active": {
                "BOOL": false
            },
            "highlight": {
                "BOOL": true
            },
            "x": {
                "N": "2094"
            },
            "y": {
                "N": "2038"
            }
        }
    }
}
}

答案 1 :(得分:0)

这个排序函数将按照它们与现在的接近程度的顺序返回值:

const res = arr.sort((a,b) => {
  if (Math.abs(now - a.from) > Math.abs(now - b.from)) {
    return 1
  }
  if (Math.abs(now - b.from) > Math.abs(now - a.from)) {
    return -1
  }
  return 0
} );

答案 2 :(得分:0)

Array.sort 所采用的函数应该是一个 compareFunction(它比较数组中的元素),而不是 keySelector


可以先提取key,按key排序,然后取回数组。

const arr = [{from: 690}, {from: 654}, {from: 618}, {from:260}];

const now = 574.49263;

function OrderBy(arr,keySelector){
  return arr.map(x=>[x,keySelector(x)]) // pair of (element, key)
     .sort((x,y)=>x[1]-y[1]) // order by key
     .map(x=>x[0])  // select element
}
const res = OrderBy(arr,item => Math.abs(item.from - now)); // abs for distance

console.log(res)

相关问题