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

如何用JavaScript实现数组指定元素移至首尾并保留其余元素顺序?

JavaScript 调整数组元素位置实现方案

需求:将数组 ['B', 'D', 'I', 'M', 'Other', 'T', 'U'] 调整为 ['T', 'B', 'D', 'I', 'M', 'U', 'Other'],要求把 'T' 移到数组开头,'Other' 移到数组末尾,其余元素保留原有顺序。

下面是两种实用的实现方式:

方法一:生成新数组(不修改原数组)

这种方式会创建新数组,原数组保持不变,适合需要保留原始数据的场景:

const originalArr = ['B', 'D', 'I', 'M', 'Other', 'T', 'U'];
// 定义需要调整位置的目标元素
const targetT = 'T';
const targetOther = 'Other';
// 过滤出除目标元素外的其他元素,保留原有顺序
const restElements = originalArr.filter(item => item !== targetT && item !== targetOther);
// 重组得到目标数组
const newArr = [targetT, ...restElements, targetOther];

console.log(newArr); // 输出: ['T', 'B', 'D', 'I', 'M', 'U', 'Other']

方法二:直接修改原数组

如果不需要保留原数组,可以直接在原数组上操作,节省内存开销:

const arr = ['B', 'D', 'I', 'M', 'Other', 'T', 'U'];

// 把'T'移到开头
const tIndex = arr.findIndex(item => item === 'T');
if (tIndex !== -1) {
  arr.splice(tIndex, 1); // 删除原位置的'T'
  arr.unshift('T'); // 将'T'插入数组开头
}

// 把'Other'移到末尾
const otherIndex = arr.findIndex(item => item === 'Other');
if (otherIndex !== -1) {
  arr.splice(otherIndex, 1); // 删除原位置的'Other'
  arr.push('Other'); // 将'Other'添加到数组末尾
}

console.log(arr); // 输出: ['T', 'B', 'D', 'I', 'M', 'U', 'Other']

你可以根据是否需要保留原数组的需求,选择对应的实现方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:55:16