Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing Array value to first Index

Tags:

javascript

var Config = {
   Windows: ['apple','mangi','lemon']
}

I have a condition and based on that i want to Push the banana value in my Array.

If(Condition Passed) {
      Config.Windows.unshift('banana');
      Windows: ['banana','apple','mangi','lemon']
      Config.Windows.reverse();
      // The way the Array elements are now reversed and First banana is accessed. 
    } else { 
      Config.Windows.reverse();     
} 

It does not do it... when i use the Config.Windows in my other function there is no banana Value... at all

for each(var item in Config.Windows.reverse()) {
 Ti.API.info(item);
 //This does not print banana
like image 744
John Cooper Avatar asked Jun 15 '11 13:06

John Cooper


People also ask

How do you push a value to the beginning of an array?

The unshift() method adds new elements to the beginning of an array.

How do you push an element in an array at first position in typescript?

Use unshift . It's like push , except it adds elements to the beginning of the array instead of the end.

What is the first index value of an array?

Definition. An array is an indexed collection of data elements of the same type. 1) Indexed means that the array elements are numbered (starting at 0).

How do I return the first index of an array?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

There are many ways in which you can push the value to the front of the array. Immediately, I can think of two ways:

  • Create a new array, and replace the old one

    if (condition) {
        Config.Windows = ['banana'].join(Config.Windows)
        Config.Windows.reverse();
    } else {
        Config.Windows.reverse();
    }
    
  • Based on what you've said, it would make more sense to always reverse the array, then push your value:

    //initial array: ['apple','mangi','lemon']
    
    Config.Windows.reverse(); //['lemon','mangi','apple']
    if (condition) {
        //this will get the same result as your code
        Config.Windows.push("banana"); //['lemon','mangi','apple', 'banana']
    }
    
like image 168
NT3RP Avatar answered Sep 22 '22 04:09

NT3RP


"The unshift is not supported by IE so if that's your browser it explains why it's not working. "

http://msdn.microsoft.com/en-us/library/ie/ezk94dwt(v=vs.94).aspx

like image 26
Jon Avatar answered Sep 19 '22 04:09

Jon