Answer the question
In order to leave comments, you need to log in
JS arrays and loops problem?
Good day to all!
There is a task (photo above) and there is a solution that I came up with (code below)
Please give feedback - how appropriate is this solution .. It works, but I would like to know what can be improved or optimized, or is it possible to do with one cycle altogether?
We are talking about the second part of the task, where you need to change the array itself, and not returning a new array.
Thank you all in advance for your constructive responses!
function reverseArrayInPlace(array){
let tempArray = [] // Временный массив
let length = array.length // Длина массива (выведена в отдельную переменную для корректной работы for)
for(let i = 0; i < length; i++){
tempArray.push(array.pop())
}
for(let i = 0; i < length; i++){
array.push(tempArray[i])
}
}
const array = [0, 1, 2, 3, 4, 5, 'any string', true, 1.3]
reverseArrayInPlace(array)
Answer the question
In order to leave comments, you need to log in
Better, probably, without a temporary array, honestly in-place:
you take a couple of elements and swap them.
// a и b взаимно обменялись значениями:
[ a, b ] = [ b, a ];
const arr = [1, 2, 3, 4, 5];
[arr[0], arr[4]] = [arr[4], arr[0]];
arr // [5, 2, 3, 4, 1]
function reverseArray(arr) {
let j = arr.length - 1;
for (let i = 0; i < arr.length / 2; i++) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
}
return arr;
}
On Habré, I accidentally stumbled upon a comment with a good solution! Who cares..
function reverseArrayInPlace(array){
for( let i = 0; i < array.length; i++ ){
array.splice(i, 0, array.pop())
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question