简体   繁体   中英

Reversing certain number of elements in an array javascript

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);

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.

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

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.

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>

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);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM