Search code examples
javascriptarrayssortingsub-array

How to sort only part of array? between given indexes


I have an array of numbers and I need to sort only part of it by left and right barriers. Can you please help me how to implement it correctly?

const sortBetween = (arr, left, right) => {
   ...
}
given: [9,3,5,7,4,9,4,1] , left = 2, right = 5
expected: [9,3,4,5,7,9,4,1]

[9,3,5,7,4,9,4,1] -> [9,3,4,5,7,9,4,1]

Thanks for the help.


Solution

  • This is an approach by using sort directly, but shaping the access with a Proxy for length and the indices.

      type        original array       length
    -------  ------------------------  ------
    values    9  3  5  7  4  9  4  1       8
    indices   0  1  2  3  4  5  6  7
    -------  ------------------------  ------
    
      type          proxy view         length
    -------  ------------------------  ------
    values          5  7  4  9             4
    indices         0  1  2  3
    -------  ------------------------  ------
    

    const
        sortBetween = (array, left, right) => {
            new Proxy(array, {
                get (target, prop) {
                    if (isFinite(prop)) return target[+prop + left];
                    if (prop === 'length') return right - left + 1;
                    return target[prop];
                },
                set (target, prop, receiver) {
                    target[+prop + left] = receiver;
                    return true;
                }
            })
            .sort((a, b) => a - b);
    
            return array;
        };    
        
    console.log(...sortBetween([9, 3, 5, 7, 0, 9, 4, 1], 2, 5)); // [9, 3, 0, 5, 7, 9, 4, 1]