You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按嵌套键值将对象按字母顺序插入数组时的排序异常问题

问题原因与修复方案

问题根源

你的代码中,当待插入元素比myList中所有已存在元素都大时,lodash.findIndex会返回-1。此时调用myList.splice(-1, 0, item)并不会将元素插入到数组末尾,而是插入到倒数第二个位置——这就是Pear排序错误的核心原因:后续插入的Strawberry比Pear大,插入时挤掉了Pear的正确位置,最终导致Pear出现在数组最后。

修复代码

只需要在获取插入索引后,处理index === -1的情况,将索引设为数组长度(即插入到末尾):

import { findIndex } from 'lodash';

let myList = [];

mockHttp()
  .then((res: Array<any>) => {
    console.log(res)
    res.forEach(item => {
      let index = findIndex(myList, function(listItem) { 
        return listItem.name.toLowerCase() > item.name.toLowerCase(); 
      });

      // 当没有找到更大的元素时,插入到数组末尾
      if (index === -1) {
        index = myList.length;
      }

      myList.splice(index, 0, {
        name: item.name,
        id: item.id,
        enabled: false
      })
    })

    console.log('result', myList);
  });

function mockHttp() {
   let p = new Promise(function(resolve,reject){
      resolve([
        { id: 'dscjidovvocsi', name: 'Pear' },
        { id: 'dscjidovvocsi', name: 'Banana' },
        { id: 'dscjidovvocsi', name: 'Orange' },
        { id: 'dscjidovvocsi', name: 'Blueberry' },
        { id: 'dscjidovvocsi', name: 'Grapefruit' },
        { id: 'dscjidovvocsi', name: 'Peach' },
        { id: 'dscjidovvocsi', name: 'Strawberry' },
        { id: 'dscjidovvocsi', name: 'Dragonfruit' },
        { id: 'dscjidovvocsi', name: 'Mango' },
        { id: 'dscjidovvocsi', name: 'Apples' }            
      ]);
   });

   return p;
 }

修复逻辑说明

  • 当findIndex返回-1,说明当前元素比数组中所有元素都大,此时将插入索引设为myList.length,调用splice会直接把元素追加到数组末尾。
  • 其他场景下,原逻辑保持不变,元素会被插入到第一个比它大的元素前面,维持升序排列。

内容的提问来源于stack exchange,提问作者Oam Psy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:07:15