1 Replies - 4128 Views - Last Post: 27 October 2011 - 09:52 PM

#1 cdwb77  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 20
  • Joined: 01-October 11

What method can move an array element to the front?

Posted 27 October 2011 - 08:27 AM

I'm using a prompt to let the user enter the number of an item on a list to move it to the top of the list. I've been experimenting with the splice and unshift methods but I'm not getting anywhere.

This is a very simplified version of the code. I have all of the if statements to make sure the user is entering a valid number that is within the length of the array already in my actual code, but wanted to make this shorter to look over.
var my_list = ["a","b","c","d"]  //THE USER SEES THESE ONSCREEN AS 1.a, 2.b, 3.c, 4.d

//BELOW IS PART OF A FUNCTION THAT I HAVE AN EVENT HANDLER FOR, JUST OMITTED THE EXCESS CODE
 
 var toTop = prompt("Enter the number of the task you want moved to the top of the list:", "");

toTop--;  //BECAUSE THE USER ENTERS THE NUMBER THEY SEE, BUT THE LIST ACTUALLY STARTS WITH ZERO

my_list.unshift(my_list[toTop]); // SHOULD I HAVE STORED THE VALUE OF my_list[toTop] IN A VARIABLE FIRST?
                                 // BECAUSE I DID TRY THAT BUT IT DIDN'T SEEM TO MAKE A DIFFERENCE 
var takeOut = my_list.indexOf(my_list[toTop],1);  //MY ATTEMPT TO LOCATE THE POSITION OF THE USER'S PICK SO I CAN
my_list.splice(takeOut,1);                        // REMOVE IT FROM THE LOWER PART OF THE LIST



I realize that this might be way off but I'm new at this so be kind please! :helpsmilie:

Is This A Good Question/Topic? 0
  • +

Replies To: What method can move an array element to the front?

#2 cdwb77  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 20
  • Joined: 01-October 11

Re: What method can move an array element to the front?

Posted 27 October 2011 - 09:52 PM

Nevermind!! I figured it out. I just left out the parentheses when I called my update_my_list function, which I didn't even bother to post above because I didn't think it was the problem!
I logged in to delete my post, but... apparently that is not allowed... Sorry to waste anyone's time.

Perhaps this will help someone else with their array.

This is what I left out (if anyone cares!):
    update_my_list(); // FYI TO OTHER NOOBIES- THIS WON'T CALL YOUR FUNCTION WITHOUT THE PARENTHESES. I TRIED IT.

// AND HERE'S WHAT THAT FUNCTION DOES
var update_my_list = function () {
    if ( my_list.length == 0 ) {
        $("my_list").value = "";
    } else {
        var list = "";
        for ( var i in my_list ) {
            list += (parseInt(i)+1) + ": " + my_list[i] + "\n";
        }
        $("my_list").value = list;
    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1