JavaScript按时间戳插入对象至正确位置时的排序异常问题
问题分析与解决方案
问题原因
你的插入排序逻辑存在漏洞:当新元素的时间戳比数组中所有元素都大时,findIndex会返回-1,此时使用splice(-1, 0, newItem)会把新元素插入到数组的倒数第二个位置,而非正确的末尾。这就导致第一个插入的元素c被后续所有更大的元素不断挤到更靠后的位置,最终出现在列表末尾。
修正后的代码
// 初始化目标数组 const end = []; const insertItem = (newItem) => { if (end.length === 0) { end.push(newItem); return; } // 提前计算新元素的Date对象,避免重复创建 const newItemDate = new Date(newItem.tstmp); const insertIndex = end.findIndex(item => new Date(item.tstmp) > newItemDate); if (insertIndex === -1) { // 所有元素都小于等于新元素,插入到末尾 end.push(newItem); } else { // 插入到第一个比新元素大的元素前面 end.splice(insertIndex, 0, newItem); } }; // 待排序数组 const arr = [ { tstmp: "2022-12-13T10:36:35.164165+0100", name: "c" }, { tstmp: "2022-12-13T10:18:33.798261+0100", name: "b" }, { tstmp: "2022-12-14T12:54:50.109871+0100", name: "a" }, { tstmp: "2022-12-13T10:18:36.161500+0100", name: "d" }, { tstmp: "2022-12-13T10:36:30.584337+0100", name: "e" }, { tstmp: "2022-12-14T13:07:23.681388+0100", name: "f" }, { tstmp: "2022-12-14T16:07:23.681388+0100", name: "g" }, ]; // 执行插入排序 for (let i = 0; i < arr.length; i++) { insertItem(arr[i]); } console.log(end);
修正后输出结果
[ { tstmp: '2022-12-13T10:18:33.798261+0100', name: 'b' }, { tstmp: '2022-12-13T10:18:36.161500+0100', name: 'd' }, { tstmp: '2022-12-13T10:36:30.584337+0100', name: 'e' }, { tstmp: '2022-12-13T10:36:35.164165+0100', name: 'c' }, { tstmp: '2022-12-14T12:54:50.109871+0100', name: 'a' }, { tstmp: '2022-12-14T13:07:23.681388+0100', name: 'f' }, { tstmp: '2022-12-14T16:07:23.681388+0100', name: 'g' } ]
额外优化
- 提前计算新元素的
Date对象,避免在findIndex的回调中重复创建,提升循环插入的性能。 - 变量名更具语义化(如
insertIndex替代x),增强代码可读性。
内容的提问来源于stack exchange,提问作者Flap13
相关产品推荐
相关产品推荐

