V
V
Vladislav Vorobyov2022-03-26 17:56:51
JavaScript
Vladislav Vorobyov, 2022-03-26 17:56:51

JS arrays and loops problem?

623f28cae5376969829588.png

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

4 answer(s)
S
Sergey Sokolov, 2022-03-26
@Voroba1996

Better, probably, without a temporary array, honestly in-place:
you take a couple of elements and swap them.

  • First with last.
  • Second with penultimate.
  • ?????
  • Profit!
In the loop, you will have to go through only half the array.
syntax

Современный синтакс позволяет менять местами два элемента без временной переменной:
// 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]

K
kim_saakyan, 2022-03-26
@kim_saakyan

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;
}

V
Vladislav Vorobyov, 2022-03-27
@Voroba1996

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())
    }
}

As for me, this is very
elegant)
link to the comment: https://habr.com/ru/post/240813/#comment_8075865

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question