使用js写一个方法,使得数组的某个元素置顶
/**
* Moves the element at the specified index to the beginning of the array.
*
* @param {Array} arr The array to modify.
* @param {number} index The index of the element to move to the top.
* @returns {Array} The modified array with the element at the top. Returns the original array if the index is invalid.
*/
function moveToTop(arr, index) {
if (index < 0 || index >= arr.length) {
return arr; // Invalid index, return original array
}
const element = arr.splice(index, 1)[0]; // Remove the element at the specified index
arr.unshift(element); // Add the removed element to the beginning of the array
return arr;
}
// Example usage:
const myArray = ['apple', 'banana', 'orange', 'grape'];
console.log(moveToTop(myArray, 1)); // Output: ['banana', 'apple', 'orange', 'grape']
console.log(moveToTop(myArray, 3)); // Output: ['grape', 'banana', 'apple', 'orange']
// Example with invalid index:
console.log(moveToTop(myArray, -1)); // Output: ['grape', 'banana', 'apple', 'orange'] (no change)
console.log(moveToTop(myArray, 4)); // Output: ['grape', 'banana', 'apple', 'orange'] (no change)
// More robust version using slice to avoid modifying the original array if the index is invalid:
function moveToTopImmutable(arr, index) {
if (index < 0 || index >= arr.length) {
return arr.slice(); // Return a copy of the original array
}
return [arr[index], ...arr.slice(0, index), ...arr.slice(index + 1)];
}
const myArray2 = ['apple', 'banana', 'orange', 'grape'];
console.log(moveToTopImmutable(myArray2, 1)); // Output: ['banana', 'apple', 'orange', 'grape']
console.log(myArray2); // Output: ['apple', 'banana', 'orange', 'grape'] (original array unchanged)
This code provides two functions:
moveToTop(arr, index)
: Modifies the original array directly. If you need to preserve the original array, use the second function.moveToTopImmutable(arr, index)
: Creates a new array with the element moved to the top, leaving the original array unchanged. This is generally preferred in functional programming paradigms. It uses the spread syntax (...
) for a concise way to create the new array.
Both functions handle invalid indices gracefully by returning the original array (or a copy of it in the immutable version). The examples demonstrate how to use the functions and show the output. The comments explain the logic clearly.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了