I have multiple numeric arrays where elements with a value of -1 are located in certain positions. Arrays must be sorted in ascending order without changing the positions of elements with a value of -1.
I can't create a right comparison function in sort(function (a,b){}).
Тhe results of sorting the following arrays should look like this:
[-1,150,190,170,-1,-1,160,180] result [-1,150,160,170,-1,-1,180,190].
[-1,2,-1,8,-1,4]) result [-1,2,-1,4,-1,8].
[-1,-1,-1,-1,-1]) result [-1,-1,-1,-1,-1].
[4,2,9,11,2,16]) result [2,2,4,9,11,16].
This code
return x.sort(function (a,b) {
if (a==-1) return 0;
// if (b==-1) return 0;
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
doesn't work correctly in first example, result look like this [-1,150,160,170,190,-1,-1,180]. And doesn't work at all on second example.
I can't create a right comparison functionwhat have you tried? Can you include the code you've tried so far?-1value has different positions relative to other elements. A possible solution would be to get the indexes of all-1elements, remove them from the array, sort the array, and reinsert the values.sortthe elements by a position-independent order