I have an array like ['a','b','c','d','e','f']
and I want to reverse only a part that I filter previously, for example I filter and I get ['c','d','e']
and I do reverse and the final result that I expected is ['a','b','e','d','c','f']
.
I've tried to do array.slice().filter(condition).reverse()
, and another solutions from stackoverflow but no one worked for me.
Any idea?
if you know the starting index and length of sub-array you want to reverse
const arr = ['a','b','c','d','e','f'];
function reverse(arr, i, j){
while(i <j){
const temp = arr[i]
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
return arr;
}
const result = reverse(arr, 2, 4)
console.log(result) // ["a", "b", "e", "d", "c", "f"]
the code above will solve your problem in time complexity of O(n)