javascript - array.push(newItem) is breaking the function.

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

02-Sep-17 06:36
Hi all, I am new to javascript, and I'm having an issue with a dropdown box in html (<select>).

The problem is that I need to re-arrange an array the add the first value on the end. However, whenever I try adding the first item to the end the whole function breaks! Here is what I'm working with:


<p id="selectedItemLabel"></p>
<select id="dropDownItems">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>

The JS:

function rearrangeAndDisplay() {
var myArray = ["A", "B", "C", "D"];
var selectedDropDown = document.getElementById("dropDownItems");
var selectedItemIndex = selectedDropDown.selectedIndex;
var selectedItemFromDropDown = selectedDropDown.options[selectedItemIndex].text;

document.getElementById("selectedItemLabel").innerHTML = "Selected Item is: " + selectedItemFromDropDown;

var myRearrangedArray = myArray.slice(selectedItemIndex) + myArray.slice(0, selectedItemIndex);

// This is the line that messes everything up:


document.getElementById("dropDownItems").addEventListener("change", rearrangeAndDisplay);

Without the line with the push() function everything works like its supposed to, however none of the function works with the line.

So with default selected it should be C, D, A, B, C (the first value added on the end), but it doesnt work.

If I take out the push() function I get C, D, A, B like i should, and when a different item is chosen from drop-down menu it changes and displays everything like it should.

I am relatively new to javascript and just doing a little script to learn and practice (actually porting a python terminal program to JS for better UI, so I have written a functioning version in python, but syntax and functionality is different in JS). If anyone could shed some light on what i'm doing wrong i would greatly appreciate it.

EDIT: Heres a jsfiddle to see it in action -

[Edited by lostCause on 02-Sep-17 07:19]
02-Sep-17 07:33
I figured it out, i should have been using:

myRearrangedArray = myArray.slice(selectedItemIndex).concat(myArray.slice(0, selectedItemIndex));

What i didn't realize is that the "+" was adding the last element and the first one (D and A), and somehow was hurting it.

Sorry for posting such a trivial issue, I didn't mean to spam a bunch of code... but it was driving me crazy!

Anyways thanks for having me and sorry again.

[Edited by lostCause on 02-Sep-17 07:37]

New posts
Old posts

Follow Elated