skip to Main Content

Here’s what i’m trying to do. I have an Array arr with strickly 4 elements. can’t have more and can’t have less. I have another Array called shiftAmounts.
So here’s what I have and the result i’m looking for…

arr[A, B, C, D]
shiftAmounts[0, 1, 1, 3]
result: arr[A,"Empty", B, C]

So starting from the right (the fouth elements) it<s important, I have to move the D to the right by 3 space. Since I can’t have more than 4 elements, then it’s deleted
Next the C move one space to the right
Next the B move one space to the right
Next the A don’t move cause it has 0.
Elements never cross each others.
The change has to be in place.
tks for your help
Seby

2

Answers


  1. i have made a function for you which can achieve you desired outcome

    function shiftArray(arr, shiftAmounts) {
      for (let i = 3; i >= 0; i--) {
        const shift = shiftAmounts[i];
        if (shift === 0) continue;
    
        const newIndex = i + shift;
        if (newIndex >= 4) {
          arr.splice(i, 1);
          continue;
        }
    
        arr[newIndex] = arr[i];
        arr[i] = "Empty";
      }
      return arr;
    }
    
    const arr = ["A", "B", "C", "D"];
    const shiftAmounts = [0, 1, 1, 3];
    const result = shiftArray(arr, shiftAmounts);
    console.log(result);
    Login or Signup to reply.
  2. Map each element of the array to a list of elements and new positions.

    Then, use Object.fromEntries to treat that array as a list of key-value pairs and create an object from them, and use Array.from to convert that into an array. Note that Array.from will automatically exclude elements in positions greater than the specified array length.

    The second parameter to Array.from is an arrow function that replaces missing array elements with the string ‘Empty’.

    const arr = ['A', 'B', 'C', 'D']
    const shiftAmounts = [0, 1, 1, 3]
    
    const r = Array.from({
      length: arr.length,
      ...Object.fromEntries(arr.map((e,i) => [i+shiftAmounts[i], e]))
    }, e => e ?? 'Empty')
    
    console.log(r)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search