Nodejs Array Reverse reversed(array)

Here you can find the source of reversed(array)

Method Source Code

// The Array's reverse() method has gone missing! Re-write it, quick-sharp!

// When this method is called, it reverses the order of the items in the array it is called on, and then returns that same array.

// Here's an example:

var input = [1, 2, 3, 4];
input.reverse(); // == [4, 3, 2, 1]  // returned by .reverse()
input;           // == [4, 3, 2, 1]  // items reordered in the original array


// My solution:/*from w w  w  . ja va  2s  . c  o  m*/

Array.prototype.reversed = function(array) {
  var reverse = [];
  for (var i = 0; i<this.length; i++) {
     reverse[i] = this[this.length - i - 1];
  }
  return reverse;
};

Related

  1. reverse(fn)
    Array.prototype.reverse = function(fn) {
      for (var i = this.length - 1; i >= 0; i--) fn(this[i]);
    
  2. reverse1()
    Array.prototype.reverse1 = function() {
        var arrLength = this.length;
        for(var i = arrLength-1; i>=0; i--){
            this.push(this[i]);
        this.splice(0,arrLength);
        return this;
    };
    console.log([3,2,1].reverse1());
    ...
    
  3. reverseElements()
    "use strict";
    Array.prototype.reverseElements = function () {
        var temp = this.concat();
        var i = this.length - 1;
        var target = this.length - 1;
        while (i >= 0) {
            this[target - i] = temp[i];
            i--;
        return this;
    
  4. reverseFromLToR(left,right)
    Array.prototype.reverseFromLToR = function(left,right){
        if(right >= this.length){
            return;
        while(left < right){
            var temp = this[left];
            this[left] = this[right];
            this[right] = temp;
            left++;
    ...
    
  5. reverseFromLToR(left,right)
    Array.prototype.reverseFromLToR = function(left,right){
        if(right >= this.length){
            return;
        while(left < right){
            var temp = this[left];
            this[left] = this[right];
            this[right] = temp;
            left++;
    ...