2

I have some arrays all of equal lengths and four null values are present at random positions for each those arrays and i need to sort those array of numbers, provided the position of null is not altered.

For example, My arrays:

var arr1 = [6, 3, null, 5, null, 4, null, null];
var arr2 = [null, 7, 4, null, 6, null, 5, null];

Expected output should be: (null positions are not altered)

var arr1 = [3, 4, null, 5, null, 6, null, null];
var arr2 = [null, 4, 5, null, 6, null, 7, null];

Please Help advise or suggest somecode in the below function so to acheive this requirement in javascript

function sortByNotalterNull(arr) {

 //somecode here

 return arr;
};
sortByNotalterNull(arr1);

1 Answer 1

4

You could take a helper array for the not null indices and another for the numbers, sort them and apply them back on the previously stored indices of the original array.

const sort = array => {
        let indices = [];

        array
            .filter((v, i) => v !== null && indices.push(i))
            .sort((a, b) => a - b)
            .forEach((v, i) => array[indices[i]] = v);
        return array;
    };

console.log(...sort([6, 3, null, 5, null, 4, null, null]));
console.log(...sort([null, 7, 4, null, 6, null, 5, null]));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.