1

I am working on a code where I need to reverse certain no of elements in an array and rest should remain same. For example is an array has values of 1,2,3,4,5,6 and I have to reverse 4 elements of it then output should be 4,3,2,1,5,6. I am using below code to achieve this but getting error, please suggest.

function reverseArray(n, a) {
  var interimArray1 = [];
  //var interimArray2=[];
  //var finalArray=[];
  for (var i < n; i >= 0; i--) {
    interimArray1.push[a[i]];
  }
  for (var i = n; i < a.length; i++) {
    interimArray1.push[a[i]];
  }
  for (var i = 0; i < interimArray1.length; i++) {
    console.log(interimArray1[i]);
  }
}

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

reverseArray(num, arr);
8
  • 3
    There's a syntax error on the 5th line (var i < n part) Commented Apr 4, 2016 at 2:46
  • If you want to use exists functions, see developer.mozilla.org/fr/docs/Web/JavaScript/Reference/… and w3schools.com/jsref/jsref_reverse.asp I hope it may help Commented Apr 4, 2016 at 2:47
  • @rodorgas updated the code as below but still not working var arr = [1, 2, 3, 4, 5, 6]; var num = 4; function reverseArray(n, a) { var interimArray1 = []; //var interimArray2=[]; //var finalArray=[]; for (var i = n - 1; i >= 0; i--) { interimArray1.push[a[i]]; } for (var i = n; i < a.length; i++) { interimArray1.push[a[i]]; } for (var i = 0; i < interimArray1.length; i++) { console.log(interimArray1[i]); } } reverseArray(num, arr); Commented Apr 4, 2016 at 2:48
  • Does the num always starts with zeroth index? Commented Apr 4, 2016 at 2:48
  • 2
    a.splice(0,4).reverse().concat(a) will do the job with quite a bit less code. May not be the answer you want though… Commented Apr 4, 2016 at 2:51

6 Answers 6

2

The error in your code is that you intend to call the push method on a[i] like so:

interimArray1.push(a[i]);

but instead you write:

interimArray1.push[a[i]];

You make that mistake twice. To give arguments to the push method, you must use round parenthesis ().

With that fixed, you will see that your code works perfectly.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array#slice, Array#splice as follow.

function partialReverse(arr, num, from = 0) {
    var slicedArr = arr.slice(from, num + from);
    
    arr.splice(from, num); // Remove `num` items from array
    arr.splice(from, 0, ...slicedArr.reverse()); // Add `num` reversed items

    return arr;
}

var arr = [1, 2, 3, 4, 5, 6];
console.log(partialReverse(arr, 4, 0)); // Reverse four items from `arr` starting from 0th index
console.log(partialReverse(arr, 4, 1)); // Reverse four items from `arr` starting from 1st index

Comments

0

Lots of hints but you seem to be missing them. ;-)

You need to assign an initial value to i, so:

for (var i = n; ... )
===========^

Also, you need to use () to call functions, not [], so:

interimArray1.push(a[i]);
==================^====^

Same in the following for block. Otherwise, the code works though it's more verbose than it needs to be.

Comments

0

This is working :

I'm sure there are faster ways of doing it. Also, it will only work for elements at the beginning of the array but you can adjust the function for what you want to achieve.

var reverseArray = function(arr,elementsToReverse) {
  var tempArrayRev = [];
  var tempArray = [];
  for (var i=0;i<arr.length;i++) {
     if (i < elementsToReverse) {
       tempArrayRev[i] = arr[i];
     } else {
       tempArray.push(arr[i]);
     }
  }
    return tempArrayRev.reverse().concat(tempArray);
}

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


document.getElementById('arrayOutput').innerHTML += reverseArray(array,4);
<div id="arrayOutput">Array :<br></div>

Comments

0

This is the answer you can test it.

        function reverseArray(n, a) {
            var interimArray1 = [];

            for (var i = 0; i < a.length; i++) {
              interimArray1.push(a[i]);
            }
        for (var i = num; i >=0; i--) {
            interimArray1[i-1] = a[n - i];
        }
        for (var i = 0; i < interimArray1.length; i++) {
            console.log(interimArray1[i]);
        }
        }

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

        reverseArray(num, arr);

Comments

-1

You could use something like this.

function reverseArray(n, arrIn) {
    // Splice splits the array in 2 starting at 0 index going n long
    var arrOut = arrIn.splice(0,n);
    // reverse is pretty straight forward
    arrOut = arrOut.reverse();
    // Concat joins the two together
    return arrOut.concat(arrIn);
}

4 Comments

See robgs comment for a much shorter chained version.
Any reasoning for the downvote :S ? would love to fix any issue there may be with my awnser.
Not the downvoter, but possibly because you are mutating the input array?
Not my downvote, but an answer should address what is wrong in the OP's code and explain how to fix it, not just post completely different code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.