0

I have been participating in some javaScript challenges and solved the reverse array challenge without modifying the original using the spread operator. I enjoy solving problems in different ways so i'm curious to find out from you. In what other way would you have solved it or would you solve it (excluding high order functions like map etc) ?

 var newArray = [1,2,3,4,5,6];

 const reverseArray = () => {
       let arr = [...newArray];

   for(let i = 0; i <= arr.length; i++){
         arr.pop(i)
         arr.unshift(i);
   }
   return arr
 }


console.log(reverseArray())

1 Answers1

1

You can use reverse();

var newArray = [1, 2, 3, 4, 5, 6];

var reverse = newArray.reverse();
console.log(reverse)

Use a for loop with increment to set index and then decrement value and push into array

var myArray = [1, 2, 3, 4, 5, 6, 7, 8];

function reverseArray(myArray) { // create a function and pass our array into it
  var newArray = []; // define an empty array
  for (var i = myArray.length - 1; i >= 0; i--) { // set for loop, declare a decrement for index as i - 1 to adjust for index, if greater than or equal to 0, decrement i
    newArray.push(myArray[i]); // push the value into newArray
  }
  return newArray; // return newArray
}

console.log(reverseArray(myArray));

Use slice() reverse() and map() together index and value through function.

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var div = document.getElementById('div')

function sliceMap() {
  reverseArray = myArray.slice(0).reverse().map(
    function(value) {
      return value;
    }
  );

  div.innerHTML =  reverseArray;
}

console.log(sliceMap())
<div id="div"></div>

Mapping values and then using unshift to reverse them.

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var reverseArray = [];

myArray.map((value) => {
  reverseArray.unshift(value);
});

console.log(reverseArray)
dale landry
  • 7,831
  • 2
  • 16
  • 28