Offset index of an array

const numbers = [1,2,3,4];
const output =move(numbers,1,-1);
 [2,1,3,5,4] console.log(output);
 function move(array,index,offset){ }

https://www.freecodecamp.org/news/swap-two-array-elements-in-javascript/
 


/**
 * Move an element
 * input ->[1,2,3,4,5];
 * move(arr,index,offset)
 * 
 * we should not modify the orignal array
 * 
 * if not possible --> invalid
 * move(input,0,-1)
 * 
*/

const move =(arr,index,offset)=>{
  const position =index+offset;
  
  if(position>=arr.length||position<0){
   
    return 'Invalid';
  }
  
  const clone =[...arr];
  let element=clone.splice(index,1)[0];
  clone.splice(position,0,element)
  return clone;

}
const arr=[1,2,3,4,5];
console.log(move(arr,0,5))


 





Comments

Popular posts from this blog

TO the new

4048