编辑代码


function swapArrayElements(arr: any, key: number) {
    // 查找key1在数组中的索引
    const index = getKeyIndex(arr, key);
    console.log(index)    
    // 检查用户名是否在数组中
    if (index === -1 ) {
      throw new Error('One or both users not found');
    }
   if (index !== -1 && (index-1) !== -1) {
         [arr[index], arr[index-1]] = [arr[index-1], arr[index]];
        }
    return arr
}

// 查找key在数组中的索引
function getKeyIndex(arr: any, key: any) {
  return arr.findIndex((item: { key: any }) => item.key === key);
}
const originalArray= [
    { key: 1, value: 'A' },
    { key: 2, value: 'B' },
    { key: 3, value: 'C' },
    { key: 5, value: 'D' },
    { key: 4, value: 'E' },
];
let res = swapArrayElements(originalArray,5)
console.log(res)