Как перевернуть массив в js
Перейти к содержимому

Как перевернуть массив в js

  • автор:

Reversing an Array in javaScript with lodash _.reverse, and alternatives

For todays lodash post I have come around to taking a moment to write a quick post about _.reverse. Lodash is a great project, but many of the methods are pretty much just reverences to native methods, and _.reverse is an example of one of these. Also the native array method on which _.reverse is based has excellent backward compatibility, as the method will work on browsers as old as IE 5.5.

So then _.reverse is not one of those lodash methods that help support a case that lodash acts as a safety net of sorts when it comes to the question of supporting older browsers. At least it is worth saying that the lodash reverse method is not the best example of safely net types methods in lodash. Never the less in this post I will be writing about _.reverse and the native Array.reverse methods as a means to reverse the order of an array in javaScript, and also cover some any and all related topics that might pop up in the process of doing so.

1 — What to know

This is a post on the _.reverse method in lodash that can be used to reverse the order of an array in javaScript, as well as other related topics. This is not a getting started post with lodash, or javaScript in general, and I assume that you have at least some background with these topics.

2 — Basic example of _.reverse and Array.reverse

So for a basic example of _.reverse I just have a quick code example in which I am just reversing the array by passing the array to _.reverse.

The native Array.reverse works by just calling it off the instance of Array.

That is all there is to it, not must to write about with this one. However there is the matter that _.reverse is a method that will not return a new array, but mutate the existing one that is passed to it. In most cases this does not present a problem, unless for some reason it does, in which case there will be a need to clone the array first, or write a custom reverse method.

3 — Using _.clone to clone the array before reversing

So if lodash is part of the stack then there is or course methods like _.clone, _.cloneDeep, _.create, and so forth to work with that can be used to make both shallow, and deep clones of objects including arrays.

So if lodash is there to work with, then it is no problem at all to address the mangle rather than create new nature of _.reverse. If you are going vanilla js style though there are some quick solutions that can help as well.

4 — reversing without managing with plain old javaScript

4.1 — Writing a method

Its not like writing an reverse method is that hard if it seems like that is what just needs to happen

A solution like this would work on a wide range of platforms, but if you do not care that much about older browsers there are a number of methods than can be used to clone an array before reversing it.

4.2 — Array.from

The native Array.from can be used to quickly create a new array from an array.

5 — Conclusion

So then _.reverse in lodash is one of those methods in lodash that are there pretty much just for the sake of consistency, and they do not do much of anything differently from what is available in javaScript by itself. Of course this is not the case with all lodash methods, and if methods like this really bother you lodash methods can be quickly installed on a per method basis.

JavaScript Reverse Array – Tutorial With Example JS Code

JavaScript Reverse Array – Tutorial With Example JS Code

Reversing an array with certain restrictions is one of the most common challenges you will find in job interviews and coding quizzes.

This tutorial will show you five ways to reverse an array in JavaScript with and without the reverse method, along with code snippets that you can use.

How to Reverse an Array in JavaScript with the Reverse Method

When you need to reverse an array in JavaScript, you can use the reverse method, which will put the last element first and the first element last:

Reversing an array with JavaScript

But keep in mind that the reverse method will also modify the original array:

Reverse method modifies the original array

Some coding challenges may want you to preserve the original array, so let’s look at how you can reverse an array without changing the original.

How to Reverse an Array in JavaScript with the Spread Operator

You can use a combination of the spread operator and the reverse method to reverse an array without changing the original.

First, you put the elements returned from the spread operator into a new array by enclosing the spread syntax with square brackets [] :

Then, you call the reverse method on the array. This way, the reverse method will be executed on the new array instead of the original:

Using spread and reverse to reverse the array

Note: the spread method is ES6 syntax. When you need to support older browsers or you want to use ES5 syntax, you can combine the slice and reverse methods. Let’s look at that now.

How to Reverse an Array in JavaScript with the Slice and Reverse Methods

The slice method is used to return the selected elements as a new array. When you call the method without any argument, it will return a new array that’s identical to the original (from the first element to the last).

Next, you call the reverse method on the newly returned array. This is why the original array is not reversed:

Using slice and reverse methods to reverse the array

How to Reverse an Array in JavaScript Without the Reverse Method

Sometimes a job interview will challenge you to reverse an array without the reverse method. No problem! You can use the combination of a for loop and an array push method like in the example below:

Reversing an array with for loop and push method

How to Write your Own Reverse Function in JS

Finally, let’s say you’re tasked with writing your own reverse function that needs to reverse an array without creating a copy. This might seem complicated at first, but don’t worry because it’s actually quite easy.

What you need to do here is to swap the first and last elements of the array, then the second and second-to-last elements, and so on until you’ve swapped all the elements.

js-array-reverse-function-1

A function to reverse an array

Let’s write a function to do just that.

Write the function customReverse and store both the first index at 0 and the last index using array.length — 1 as variables.

Next, create a while loop that runs as long as the leftIndex is smaller than the rightIndex .

Inside this loop, swap the value of the leftIndex and the rightIndex . You can temporary store one of the values in a temporary variable:

Finally, move the leftIndex up and the rightIndex down. When the while loop repeats, it will swap the second and second-to-last elements, and so on:

The complete reverse array code

The loop will stop right when there are no more elements to reverse. For odd-sized arrays, the value of leftIndex and rightIndex will be equal, so no more swapping. For even-sized, the leftIndex will be greater than the rightIndex .

You can test the function to see if it works properly like this:

Testing reverse array function

Conclusion

Congratulations! You’ve learned not only how to reverse an array in JavaScript, but also how to write your own reverse function.

Обратный массив в JavaScript

В этом посте мы обсудим, как инвертировать массив в JavaScript.

1. Использование Array.prototype.reverse() функция

Стандартный метод реверсирования массива в JavaScript использует метод reverse() метод. Этот метод работает на месте, что означает, что исходный массив изменен, а обратная копия не создается.

Если вы не хотите изменять исходный массив, вызовите метод reverse() метод на копии массива. Вы можете клонировать массив с помощью оператора slicing или ES6 Spread.

2. Использование Array.prototype.map() функция

The map() метод часто используется для создания нового массива, где каждый элемент является результатом некоторой операции, примененной к элементам другого массива. Чтобы перевернуть массив, вы можете сделать так:

Следующий код использует оператор Spread для клонирования массива, а затем использует map() способ вызова pop() в исходном массиве и переместите возвращенный элемент в новый массив.

3. Использование библиотеки Lodash

Если вы используете библиотеку JavaScript Lodash в своем проекте, вы можете использовать reverse() метод для реверсирования массива на месте.

4. Пользовательская программа

Наконец, вы можете написать свою собственную процедуру, которая реверсирует массив на месте или возвращает обратную копию его экземпляра.

Вот и все, что нужно для обращения массива в JavaScript.

Оценить этот пост

Средний рейтинг 5 /5. Подсчет голосов: 20

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using array s, and I want to add a function that the user can reverse the list. I can’t think of any possible method, so if anybody knows how, please help.

Derek 朕會功夫's user avatar

36 Answers 36

Javascript has a reverse() method that you can call in an array

Not sure if that’s what you mean by ‘libraries you can’t use’, I’m guessing something to do with practice. If that’s the case, you can implement your own version of .reverse()

Do note that the built-in .reverse() method operates on the original array, thus you don’t need to reassign a .

Patrick Reck's user avatar

Andreas Wong's user avatar

Rohit Shelhalkar's user avatar

Heres a functional way to do it.

20 bytes

Concise and leaves the original unchanged.

Ali Mirzaei's user avatar

The shortest reverse method I’ve seen is this one:

Shortest reverse array method without using reverse method:

a.pop method takes an last element off and puts upfront with spread operator ()

MDN links for reference:

parag patel's user avatar

Rashid Iqbal's user avatar

This is what you want:

Here is a version which does not require temp array.

I’ve made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.

Łukasz Jagodziński's user avatar

53 bytes

Just for fun, here’s an alternative implementation that is faster than the native .reverse method.

Derek 朕會功夫's user avatar

Kangudie Muanza - Killmonger's user avatar

Above will reverse your array but modifying the original. If you don’t want to modify the original array then you can do this:

aristotll's user avatar

Using .pop() method and while loop.

I’m not sure what is meant by libraries, but here are the best ways I can think of:

As others mentioned, you can use .reverse() on the array object.

However if you care about preserving the original object, you may use reduce instead:

Michael P. Bazos's user avatar

Pure functions to reverse an array using functional programming:

It can also be achieved using map method.

Or using reduce (little longer approach)

reverse in place with variable swapping (mutative)

Reverse by using the sort method

  • This is a much more succinct method.

Using ES6 rest operator and arrow function.

Ankit Sinha's user avatar

Use swapping and return the original array.

Penny Liu's user avatar

Infact the reverse() may not work in some cases, so you have to make an affectation first as the following

or use concat

Smaillns's user avatar

What about without using push() !

Solution using XOR !

ErcanE's user avatar

JavaScript already has reverse() method on Array, so you don’t need to do that much!

Imagine you have the array below:

Now simply just do this:

and you get this as the result:

But this basically change the original array, you can write a function and use it to return a new array instead, something like this:

Or simply chaning JavaScript built-in methods for Array like this:

and you can call it like this:

Just as mentioned, the main difference is in the second way, you don’t touch the original array.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *