将元素放到数组的最前头的新思路

2022-03-23  本文已影响0人  春木橙云

新思路,记录在此,以备后查!

需求:将targetList数组中,isPoint为true的对象拿到数组前面,最终展现为,isPoint为true的对象全部排在数组前面。
targetList: [
  {
    isPoint:true,
    id:1
  },
  {
    isPoint:false,
    id:2
  },
  {
    isPoint:true,
    id:3
  },
  {
    isPoint:false,
    id:4
  },
]
我原来的方法:
  const unshiftEle = (element: any, targetArr: any[]) => {
    const data = (targetArr || []).filter(item => item.id !== element.id);
    data.unshift(element);
    return data;
  };

unshift会改变原数组,不安全;

新的方法:
  const unshiftEle = (element:any) => {
    return (targetArr || []).sort((a, b) => b. isPoint - a. isPoint)    
  };

分享大家,共同进步!

上一篇下一篇

猜你喜欢

热点阅读