move specific value to first index in a list angular code example

Example 1: javascript move item in array to another index

function moveArrayItemToNewIndex(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; 
};

//move index 1(b) to index 2(c)
console.log(moveArrayItemToNewIndex(["a","b","c","d"], 1, 2)); // returns ["a", "c", "b", "d"]

Example 2: change array index position in javascript by up and down click

// move up by 1 postion in Array
const moveUp=(id)=> {
  let index = arr.findIndex(e => e.id == id);
  if (index > 0) {
    let el = arr[index];
    arr[index] = arr[index - 1];
    arr[index - 1] = el;
  }
}

// move dwon by 1 postion in Array
const moveDown=(id)=> {
  let index = arr.findIndex(e => e.id == id);
  if (index !== -1 && index < arr.length - 1) {
    let el = arr[index];
    arr[index] = arr[index + 1];
    arr[index + 1] = el;
  }
}