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

技术问询:如何将数组中的数值从一个位置转移到另一个位置

How to Move a Value to a Target Position in an Array

Hey there! Let's break down how to tackle this array manipulation task using your example: transforming [1,0,2,3,4] into [0,0,1,3,4] by moving the value 1 to the position of 2, and setting its original spot to 0.

Core Logic to Follow

From your sample, here's the key behavior we need to replicate:

  • Locate the index of the value you want to move (in this case, 1 sits at index 0)
  • Find the index of the target value (here, 2 is at index 2)
  • Zero out the original position of the moving value (instead of deleting it, since the array length stays the same)
  • Replace the target position's value with the one you're moving

Code Examples

Let's look at implementations in two common languages:

JavaScript

const originalArray = [1, 0, 2, 3, 4];
const valueToMove = 1;
const targetValue = 2;

// Find the indices of our values
const moveFromIdx = originalArray.indexOf(valueToMove);
const moveToIdx = originalArray.indexOf(targetValue);

// Only modify if both values exist in the array
if (moveFromIdx !== -1 && moveToIdx !== -1) {
  // Set the original position to 0
  originalArray[moveFromIdx] = 0;
  // Put the moved value into the target position
  originalArray[moveToIdx] = valueToMove;
}

console.log(originalArray); // Output: [0, 0, 1, 3, 4]

Python

original_array = [1, 0, 2, 3, 4]
value_to_move = 1
target_value = 2

try:
    # Get indices of the values we care about
    move_from_idx = original_array.index(value_to_move)
    move_to_idx = original_array.index(target_value)
    
    # Update original position to 0
    original_array[move_from_idx] = 0
    # Place the moved value at the target position
    original_array[move_to_idx] = value_to_move
except ValueError:
    # Handle cases where either value isn't found
    print("Oops! Either the value to move or target value doesn't exist in the array.")

print(original_array)  # Output: [0, 0, 1, 3, 4]

Quick Notes for Edge Cases

  • Duplicate values: The code above uses indexOf() (JS) or index() (Python), which only finds the first occurrence of a value. If your array has duplicates (e.g., multiple 1s or 2s), you'll need to adjust the logic to select the correct indices (like looping through the array to find all matches).
  • Array length: Your sample keeps the array length the same by zeroing out the original position. If you wanted to remove the value and insert it elsewhere (changing the array length), the logic would involve splice() (JS) or pop()/insert() (Python)—but since your output maintains the original length, we stuck with the zero-out approach.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:56:51