JS 前端排序 数组指定项移动到最后

JS 前端排序 数组指定项移动到最后

在这里插入图片描述

问题来源:模仿win10文件夹中按类型排序
文件夹在上,文件在下,并且点击按类型排序后,文件夹和文件会各自按首字母进行排序

/**
 * 数组指定元素移动到最后的位置
 * @param {*} arr 需要排序的数组
 * @param {*} sourceIndex 需要移动的元素的索引
 * @param {*} targetIndex 目标索引
 */
function moveArray(arr, sourceIndex, targetIndex) {
  // splice 将目标元素替换并将原结果扔回来赋值给它
  arr[sourceIndex] = arr.splice(targetIndex, 1, arr[sourceIndex])[0];
}

var arr = [
  {
    id: 0,
    name: "Rose",
    type: "dircetory",
  },
  {
    id: 1,
    name: "Robin",
    type: "file",
  },
  {
    id: 2,
    name: "Tom",
    type: "dircetory",
  },
  {
    id: 3,
    name: "Taide",
    type: "file",
  },
  {
    id: 4,
    name: "Danni",
    type: "dircetory",
  },
];

// 索引数组(需要移动的元素索引数组)
var sourceIndexes = [];
arr.forEach((item, index) => {
  if (item.type == "file") {
    sourceIndexes.push(index);
  }
});

// 遍历索引数组,移动元素
sourceIndexes.forEach((sourceIndex) => {
  moveArray(arr, sourceIndex, arr.length);
});

// 过滤数组,去除 undefined 项
var result = arr.filter((item) => {
  return item !== undefined || !!item;
});
console.log(result);

输出结果

[
  { id: 0, name: 'Rose', type: 'dircetory' },
  { id: 2, name: 'Tom', type: 'dircetory' },
  { id: 4, name: 'Danni', type: 'dircetory' },
  { id: 1, name: 'Robin', type: 'file' },
  { id: 3, name: 'Taide', type: 'file' }
]
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码小余の博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值