Arrays are used to gather elements of the identical information category in one place. There are many methods for processing arrays, but what if you need to flip the array, i.e. swap elements in it? Consider several ways to reverse the elements of an array:

  • The Array.reverse method;

  • Applying a decreasing for loop;

  • The Array.unshift method;

  • The changeValuePosition constant.

Array.reverse() method

This method of the Array object reverses the sequence of the components of an array, placing the first element last, and the last element first, whereas modifying the existing array.

Syntax:

array.reverse()

Example:

const myArray = ['ten', 'twenty', 'thirty'];
console.log('My array:', myArray);
// expected output: "myarray: [ 'ten', 'twenty', 'thirty' ]"

const reversed = myArray.reverse();
console.log('reversed:', reversed);
// expected output: "myreverse: [ 'thirty', 'twenty', 'ten' ]"

// Careful: reverse is destructive -- it changes the original array.
console.log('My array:', myArray);
// expected output: "myarray: [ 'thirty', 'twenty', 'ten' ]"

Let's look at the basic operations and properties of an Array object. There are two ways to declare an array.

  • Method 1. You can declare an array by enclosing the values in [ ] brackets and separating them with a comma.

const fruits = ['Grape', 'Orange', 'Lemon']
for (i=0; i<fruits.length; i++) {
    console.log(fruits[i])
}

// Grape
// Orange
// Lemon

To refer to an element of an array, you need to specify the name of the array and the element number in [ ] brackets. Numbering items of an array begins with 0.

const first = fruits[0]
// Grape

const last = fruits[fruits.length - 1]
// Lemon

Array.length property contains the size of the array, i.e. the amount of items in the array.

console.log(fruits.length);
// 3
  • Method 2. You can declare an array using a constructor and the word new.

const names = new Array();
names[0] = "Andrey";
names[1] = "Diana";
names[2] = "John";

for (i = 0; i < names.length; i++) {
    console.log(names[i]);
}

//Andrey
//Diana
//John

Or you can specify the values directly in the constructor instead of specifying each value separately.

const age = new Array(45, 13, 32);
for (i = 0; i < age.length; i++) {
    console.log(age[i]);
}

//45
//13
//32

It is also possible not to specify values, then the specified number will mean the number of elements.

const cities = new Array(3);

In this case, the values of the array elements will be undefined. This method works for strings and booleans, but not for numbers. An array can store strings, numbers, and booleans.

// Storing numbers, boolean and strings in an Array
const house = ["window1", 2500, "window2", 2650, "Wall", true];

Array.forEach() method lets you execute a function on each element of an array. There are 3 options for calling this method.

1. With arrow function:

forEach((element, index, array) => { /* ... */ })

2. With common function:

forEach(callbackFn)

3. With a single line function:

forEach(function(element, index, array){ /* ... */ })

Parameters:

callbackFn - a function executed for each element (1 to 3 parameters);

element - the actual operated element in the array;

index (possible) - amount of the components in the array;

array (possible) - the array that forEach() called.

Return value: undefined value. For example, this code will display each element of an array and tell you its position:

["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => {
    alert(`${item} has a position ${index} in ${array}`);
    });

Decreasing for loop

In the following example we are moving backwards across the array applying a for loop, recording components into a new array. The original array is not changed.

const trees = ["Oak", "Spruce", "Pine", "Birch"];
const trees2 = new Array;
// decreasing for loop
for (let i = trees.length - 1; i >= 0; i--) {
    // adding an element to the end of the new array
    trees2.push(trees[i]);
}
// printing the result
console.log("Original array: " + trees + "\nReversed array: " + trees2);

// Original array: Oak,Spruce,Pine,Birch
// Reversed array: Birch,Pine,Spruce,Oak

The push() method appends one or more items to the end of the array and gives back the new size of the array.

push(element0, element1, /* ... ,*/ elementN)

elementN: elements to add to the end of the array.

Return value: The new value of the length attribute of the array from which the method was called.

For example, the following example creates an array sports and adds two elements to it, the variable total contains the size of the array:

let sports = ['football', 'basketball'];
let total = sports.push('tennis', 'hockey');

console.log(sports);
console.log(total);

//[ 'football', 'basketball', 'tennis', 'hockey' ]
//4

Array.unshift() method

This method is similar to the previous one, but instead we use the forEach method, that executes a function for every item, and the unshift() method, which appends an item to the beginning of a new array. The original array is not changed.

const years = [1956, 1981, 1989, 1992];
const years2 = new Array;
// the forEach method executes a function for each element
years.forEach(element => {
    // adding an element to the beginning of a new array
    years2.unshift(element);
});
// printing the result
console.log("Original array: " + years + "\nReversed array: " + years2);
 
// Original array: 1956,1981,1989,1992
// Reversed array: 1992,1989,1981,1956

The unshift() method appends one or more components to the start of an array and gives back the new size of the array.

unshift(element0, element1, /* ... ,*/ elementN)

elementN: items that are appended to the start of the array.

Return value: The new size of the array.

For instance, the next example creates two arrays, with numeric and string values, and adds two elements to the beginning of each array:

calories = [2951, 432, 1500, 2981];
grocery = ["pasta", "porridge", "rice"];

// adding elements to the beginning of an array
calories.unshift("1304", "502");
grocery.unshift("coffee", "sugar");

// printing the result
console.log("Calories: " + calories);
console.log("Grocery: " + grocery);

// Calories: 1304,502,2951,432,1500,2981
// Grocery: coffee,sugar,pasta,porridge,rice

ChangeValuePosition

In the previous two examples, we did not change the original array, but saved the changes in the new array. Let's see how to modify and reverse an array if not applying the Array.reverse() method.

const distance = [1523, 35478, 2012, 457, 1701];
console.log("Original array: " + distance);
const ln = distance.length;
// traverse half the length of the array
for (let i = 0; i < Math.floor(ln / 2); i++) {
    // swap opposite elements
    [distance[i], distance[ln - 1 - i]] = [distance[ln - 1 - i], distance[i]];
}
// print the result
console.log("Reversed array: " + distance);

// Original array: 1523,35478,2012,457,1701
// Reversed array: 1701,457,2012,35478,1523

In this example, we only exchange items that are the same distance from the first and last one, for example, first and last, second and penultimate, and so on. Here we use the changeValuePosition constant, which swaps the elements and returns the changed array.

const changeValuePosition = (arr, init, target) => {
    [arr[init], arr[target]] = [arr[target] ,arr[init]]; return arr
}

Parameters:

arr: an array in which the elements are swapped;

init: index of the first element to be swapped;

target: the index of the second element, swapped with the first.

Return value: modified array. For example, in the example below, elements 3 and 4 are swapped in the array:

const myArray = [15, 25, 35, 45, 55];
// copy the original array
const myArray2 = [...myArray];
// swap 3rd and 4th elements
[myArray2[2], myArray2[4]] = [myArray2[4], myArray2[2]];
// print the result
console.log("Original array: " + myarray + "\nModified array: " + myarray2);

// Original array: 15,25,35,45,55
// Modified array: 15,25,55,45,35