0

I have been trying to use the unshift function with a MD array, and I cannot get it to work accordingly.

I am using shift okay and it does what is needed like expected but unshift does not.

Below is the array which I am using:

[ [ '487', 'RINGING' ], [ '477', 'RINGING' ] ]

When I try and do an unshift on it it displays the following:

[ [ '487', 'RINGING' ], [ '477', 'RINGING' ], 2 ]

I simply need to move 477 array to the beginning like so:

[ [ '477', 'RINGING' ], [ '487', 'RINGING' ]]

The code I am using:

var channelArrStatus = [ [ '477', 'RINGING' ], [ '487', 'RINGING' ]];

function monitor_channel(event, channel) {
if (event.device_state['state'] === "RINGING") {
      var name = "User_487";
      var status = "NOT_INUSE"
      var index = 0;
      if (channelArrStatus.length === 0) {
        var chanar = new Array(name, status);
        channelArrStatus.push(chanar);
      } else {
        var found = false;
        for (var i in channelArrStatus) {
          var channelArrStatusElem = channelArrStatus[i];
          if (channelArrStatusElem[0] === name) {
            index = i;
            found = true;
            if (channelArrStatus[index][1] !== "DND") {
              channelArrStatus.push(channelArrStatus.unshift());
              setTimeout(function () {
                channelArrStatus[index][1] = status;
              }, 10000);
            }
          }   
        }
      }
    }

I cant get it to move an array to the beginning of the array as highlight above using unshift.

Any suggestions?

EDIT:JSFiddle

Studento919
  • 585
  • 2
  • 11
  • 41

2 Answers2

0

The call .unshift() prepends nothing and returns the length of the array - 2 in your case - and that's the value you are pushing.

You either want

channelArrStatus.push(channelArrStatus.shift()); // no un-

or

channelArrStatus.unshift(channelArrStatus.pop());

That said, you should use literal notation instead of the Array constructor and avoid for in enumerations on arrays.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • I dont want to shift it to the end of the array again I need to move it to the beginning, I have added a JS fiddle to the question to demonstrate this using `channelArrStatus.unshift(channelArrStatus.pop());` but to no avail – Studento919 Feb 29 '16 at 19:34
0

On this line

 channelArrStatus.push(channelArrStatus.unshift());

You are adding the length of array to the end of the array. If you want to add an element to the start of array, just call unshift.

channelArrStatus.unshift(element);
giannisf
  • 2,118
  • 1
  • 14
  • 29