Reversing an array in javascript

Array.prototype.reverse()

The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

To reverse the elements in an array without mutating the original array, use toReversed() .

Try it

Syntax

Return value

The reference to the original array, now reversed. Note that the array is reversed in place, and no copy is made.

Description

The reverse() method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

The reverse() method preserves empty slots. If the source array is sparse, the empty slots’ corresponding new indices are deleted and also become empty slots.

The reverse() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Читайте также:  Регулярные выражения php замена строки

Examples

Reversing the elements in an array

The following example creates an array items , containing three elements, then reverses the array. The call to reverse() returns a reference to the reversed array items .

const items = [1, 2, 3]; console.log(items); // [1, 2, 3] items.reverse(); console.log(items); // [3, 2, 1] 

The reverse() method returns the reference to the same array

The reverse() method returns reference to the original array, so mutating the returned array will mutate the original array as well.

const numbers = [3, 2, 4, 1, 5]; const reversed = numbers.reverse(); // numbers and reversed are both in reversed order [5, 1, 4, 2, 3] reversed[0] = 5; console.log(numbers[0]); // 5 

In case you want reverse() to not mutate the original array, but return a shallow-copied array like other array methods (e.g. map() ) do, use the toReversed() method. Alternatively, you can do a shallow copy before calling reverse() , using the spread syntax or Array.from() .

const numbers = [3, 2, 4, 1, 5]; // [. numbers] creates a shallow copy, so reverse() does not mutate the original const reverted = [. numbers].reverse(); reverted[0] = 5; console.log(numbers[0]); // 3 

Using reverse() on sparse arrays

Sparse arrays remain sparse after calling reverse() . Empty slots are copied over to their respective new indices as empty slots.

.log([1, , 3].reverse()); // [3, empty, 1] console.log([1, , 3, 4].reverse()); // [4, 3, empty, 1] 

Calling reverse() on non-array objects

The reverse() method reads the length property of this . It then visits each property having an integer key between 0 and length / 2 , and swaps the two corresponding indices on both ends, deleting any destination property for which the source property did not exist.

const arrayLike =  length: 3, unrelated: "foo", 2: 4, 3: 33, // ignored by reverse() since length is 3 >; console.log(Array.prototype.reverse.call(arrayLike)); // // The index 2 is deleted because there was no index 0 present originally // The index 3 is unchanged since the length is 3 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript Array reverse()

The reverse() method reverses the order of the elements in an array.

The reverse() method overwrites the original array.

Syntax

Return Value

Browser Support

reverse() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

JavaScript Reverse Array – Tutorial With Example JS Code

Nathan Sebhastian

Nathan Sebhastian

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:

js-array-reverse-function-1

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.

function customReverse(originalArray)

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:

 function customReverse(originalArray) < let leftIndex = 0; let rightIndex = originalArray.length - 1; while (leftIndex < rightIndex) < // Swap the elements with temp variable let temp = originalArray[leftIndex]; originalArray[leftIndex] = originalArray[rightIndex]; originalArray[rightIndex] = temp; // Move indices to the middle leftIndex++; rightIndex--; >>

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:

let myArray = [1, 2, 3, 4, 5]; customReverse(myArray); console.log(myArray); // output is [5, 4, 3, 2, 1]

Conclusion

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

Here are some more JavaScript tutorials that you may be interested in:

Источник

Reverse an Array in JavaScript

In this tutorial, we’ll take a look at how to reverse an array in JavaScript. There are a few ways to do this, and figuring out which one you’ll want to employ typically depends on your personal preference.

We’ll be reversing these two arrays:

let numArr = [1, 2, 3, 4, 5] let strArr = ['Java', 'Python', 'JavaScript'] 

Using Array.reverse()

The easiest and simplest way to reverse an array is via the reverse() method:

let numArrReversed = numArr.reverse(); let strArrReversed = strArr.reverse(); console.log(numArrReversed); console.log(strArrReversed); 

We’ve created two new variables to point to the resulting arrays:

[ 5, 4, 3, 2, 1 ] [ 'JavaScript', 'Python', 'Java' ] 

Note: The reverse() method reverses the array in-place. This means that the original num_array and string_array are reversed and the original sequence is lost.

You don’t need to create a new variable to store a pointer to these arrays in memory, since the original pointers already point to the reversed arrays:

numArr.reverse(); strArr.reverse(); console.log(numArr); console.log(strArr); 
[ 5, 4, 3, 2, 1 ] [ 'JavaScript', 'Python', 'Java' ] 

However, it’s still common practice to «assign» the result to a new variable to indicate a changed state, or to at least assign a more indicative name to the transformed array, such as array_reversed .

Reversing an Array Functionally

Functional programming is a wonderful addition to most imperative programming languages. Functional constructs allow us to perform various, even complex, transformative operations on objects and sequences with intuitive and simple instructions.

Many developers simply love using functional constructs when they can, so it’s no surprise that reversing an array is commonly done via functional constructs as well. This approach allows you to also pipe in another transformation alongside reversal, such as adding or changing the elements as well.

To reverse a array functionally in JavaScript, we’ll leverage the spread operator and the map() function:

// Preserves original array let numArrReversed = numArr.map(numArr.pop, [. numArr]); // Doesn't preserve original array let strArrReversed = [. strArr].map(strArr.pop, strArr); 

The map() method maps each popped element (removed last element) from the numArr and pushes it into a new array, which is created as a copy of numArr . By removing the last element and adding it as the first into a new array, we create a new reversed array.

The first approach deals with a frozen copy of the numArr object, and thus doesn’t modify the original array.

In the second approach, we modify the original array as we’re using the reference to the original array in the map() method, even though we create a copy of the array beforehand:

console.log('Original num_array: ' + numArr); console.log('Original string_array: ' + strArr); console.log('Reversed num_array: ' + numArrReversed); console.log('Reversed string_array: ' + strArrReversed); 

Thus, when all is said and done, the num_array remains unchanged, while string_array is gone:

Original num_array: 1,2,3,4,5 Original string_array: Reversed num_array: 5,4,3,2,1 Reversed string_array: JavaScript,Python,Java 

Reversing an Array with a for Loop

Finally, the good old way is to simply run the array through a for loop in backwards order, and add each element into a new array.

This works great for creating a new reversed array, but won’t reverse the old one in-place. If you’d like to reverse it in-place, you’ll want to use the unshift() method to add elements at the start of the array, while splicing (in-place operation) continually:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

function reverse(array) < let newArr = []; for(i = array.length-1; i >= 0; i--) < newArr.push(array[i]); >return newArr; > function reverseInPlace(array) < for(i = 0; i < array.length; i++) < let tmp = array.splice(i, 1)[0]; array.unshift(tmp); > return array; > 

You can use these methods as:

let numArrReversed = reverseInPlace(numArr); let strArrReversed = reverse(strArr); console.log('Original num_array: ' + numArr); console.log('Original string_array: ' + strArr); console.log('Reversed num_array: ' + numArrReversed); console.log('Reversed string_array: ' + strArrReversed); 
Original num_array: 5,4,3,2,1 Original string_array: Java,Python,JavaScript Reversed num_array: 5,4,3,2,1 Reversed string_array: JavaScript,Python,Java 

Источник

Оцените статью