使用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.