move item in array up and down

علی ذوالفقار
1402/10/26 22:16:02 (60)
// move item in an array from position to other position 
const moveItem = (arr , from , to) => {                
    let newArray = [...arr] ; // get acls from store
    var f = newArray.splice(from, 1)[0]; // remove `from` item and store it        
    newArray.splice(to, 0, f); // insert stored item into position `to`
    return newArray 
}

// move item up 
const moveItemUp = (arr , idx)=>{
    if(idx>0){ // if not first item 
        return moveItem(arr , idx , idx-1 );
    }else{
        return arr ; 
    }
}; 

// move item down 
const moveItemDown = (arr , idx)=>{
    if(idx+1 < arr.length){ // if not last item 
        return moveItem(arr , idx , idx+1 );
    }else{
        return arr ;
    }
}; 
Back