2

I want display items of an array. At the click of button I need to perform following actions:

  • Add an element at the beginning, end or middle of the displayed array
  • Sort the array
  • Remove duplicates from array

I managed to display the items of the array, and add new items, one by one with my Add in the Front button. But the string values won't show, all I can see are the index numbers 1., 2., 3., ect.

I tried putting the id="firsttree" in the <input type="text"> html tag, but the array would disappear when I load it on the web page.

JS

var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];


// Iterate array and display
originalArray.forEach(element => {
    // Creates an Element Node with the specified name.
    let listItem = document.createElement("li");

    // creates a Text Node with the specified text.
    let itemDescription = document.createTextNode(element);

    // append: Add Item or Element
    listItem.appendChild(itemDescription);

    /*document.getElementById("firsttree").innerHTML = originalArray;*/

    // Returns the element that has the ID attribute with the specified value and adds a node to the end of the list of children of the specified parent node
    document.getElementById("firsttree").appendChild(listItem);
});

/**
* Add Items to list
*/
function addItem() {
    // Unshift: Add item to beginning of list
    originalArray.unshift(document.getElementById('firsttree').value);

    // Making the text box empty and re-display
    document.getElementById('firsttree').value = " ";
    disp(); // displaying the array elements
}

/**
* Render array
*/
function disp() {

    var str=" ";
    str = originalArray.length +  '<br> '; // break the lines to form list.

    // Increment the list by 1, i++ if i is less than length
    for (i=1; i < originalArray.length;  i++) // Initial parameter is 1.
    {
        // Adding each element with key number to display string
        str += i + ". "+ originalArray[i]  + "<br> ";
    }

    // Display the elements of the array
    document.getElementById('firsttree').innerHTML=str; 
}

HMTL

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="activity3.css">
        <!-- ol: Ordered numbered list-->

        <!--<script>
            /*var trees = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];*/AbortSignal
            /*document.getElementById("oringinalTree").innerHTML = trees;*/
        </script>-->
    </head>
    <body>
        <h1>Array Methods</h1>
        <br>
        <label>
            Enter new array element here
        </label>
        <input type="text">
        <button type="button" value="Add" onclick="addItem()" >
            Add in the Front
        </button>
        <button type="text">
            Add at the End
        </button>
        <button type="text">
            Add in the Middle
        </button>
        <button type="text">
            Sort
        </button>
        <button type="text">
            Remove Duplicates
        </button>
        <br>
        </form> 

        <h2>List of Trees</h2>
        <h3>Tree Display:</h3>   
        <!-- Must create div to place list under Header-->
        <div class="originalArray">
            <ol id="firsttree"></ol>
            <!--<link rel="stylesheet" type="text/css" href="path/to/your.css" />-->
            <script src="gla3.js"></script>
        </div>
        <h4>Sorted Tree Display:</h4>
    </body>
</html>

css

h3 {
    position: absolute;
    left: 70px;
    top: 200px;
}

h4 {
    position: absolute;
    left: 300px;
    top: 200px;
}

.originalArray {
    position: absolute;
    top: 250px;
    left: 50px;
}

enter image description here

I need to add the string from input to the array and then be displayed, but instead I start off with undefined being added to array and the rest are all blank. Plus I don't want the number of increments (12) to be seen either.

Jehanzeb.Malik
  • 3,332
  • 4
  • 25
  • 41
Preston
  • 171
  • 1
  • 1
  • 9

2 Answers2

1

1: Add an id to your input element:

<input type="text" id="new_element">

2: Replace firsttree with new_element in this line:

originalArray.unshift(document.getElementById('new_element').value); //  adding element to array

3: Start your loop with i=0 in this line:

for (let i=0; i < originalArray.length;  i++)

4: Remove this line if you don't want the number of item in your array to be displayed (the 12 from your screenshot):

str = originalArray.length +  '<br> ';

Nowadays, one of the most important thing when learning a new programming language certainly is to fully understand whatever code you get from stack overflow, so don't hesitate if you want me to explain any of those steps.

Here is a example with the other functions added:

var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch',  'aspen'];

    // why not simply use your disp() function
    // to display the array at first ? 
    disp(); 


    // functions to add items

        function addItemFront() {
            originalArray.unshift(document.getElementById('new_element').value); 
            document.getElementById('firsttree').value = " "; 
            disp(); // displaying the array elements
        }
        function addItemEnd() {
            originalArray.push(document.getElementById('new_element').value); 
            document.getElementById('firsttree').value = " "; 
            disp(); 
        }
        function addItemMiddle() {
            originalArray.splice(Math.round(originalArray.length/2), 0, document.getElementById('new_element').value);
            document.getElementById('firsttree').value = " "; 
            disp(); 
        }

    // function to remove duplicate
        function removeDuplicate() {
            originalArray = array_unique(originalArray);
            document.getElementById('firsttree').value = " "; // Making the text box  blank
            disp(); // displaying the array elements
        }

        // more info on this one at: https://stackoverflow.com/questions/25530168/is-there-a-function-like-array-unique-in-jquery
        function array_unique(array){
            return array.filter(function(el, index, arr) {
                return index == arr.indexOf(el);
            });
        }

    // function to display the array
    function disp() {
        var str=" "; 
        for (i=0; i < originalArray.length;  i++){ 
            str += i + ". "+ originalArray[i]  + "<br> ";  
        } 
        document.getElementById('firsttree').innerHTML=str; 
    }

    // function to display the sorted array
    function dispSorted() {
        var str=" "; 
        var sortedArray = originalArray.sort();
        for (i=0; i < sortedArray.length;  i++){ 
            str += i + ". "+ sortedArray[i]  + "<br> ";  
        } 
        document.getElementById('sortedtree').innerHTML=str; 
    }
            .originalArray {
                position: absolute;
                top: 250px;
                left: 50px;
            }
            .sortedArray {
                position: absolute;
                top: 250px;
                left: 450px;
            }
        <h1>Array Methods</h1>
        <br>
        <div class="field">Enter new array element here</div> 
        <input type="text" id="new_element"> 
        <button type="button" onclick="addItemFront();">Add in the Front</button>
        <button type="button" onclick="addItemEnd();">Add at the End</button> 
        <button type="button" onclick="addItemMiddle();">Add in the Middle</button> 
        <button type="button" onclick="dispSorted();">Sort</button> 
        <button type="button" onclick="removeDuplicate();">Remove Duplicates</button>
        <br>
        <h2>List of Trees</h2>

        <div class="originalArray">
            <h3>Tree Display:</h3>   
            <ol id="firsttree"></ol>
        </div>

        <div class="sortedArray">
            <h4>Sorted Tree Display:</h4>
            <ol id="sortedtree"></ol>
        </div>
François Huppé
  • 2,006
  • 1
  • 6
  • 15
  • 1
    Okay thanks that really helps! I am new to Javascript and we've been learning alot of it at once, and the steps do make sense. – Preston Nov 09 '19 at 19:47
  • Also could you please help me with "Add in the middle", "Sort", and "Remove Duplicates" (Remove from Sorted Tree Display)? I've tried using numerous methods for all, but none of them worked.... – Preston Nov 09 '19 at 23:40
  • Alright it looks great! Thanks for your help! You definitely saved me allot of time. – Preston Nov 11 '19 at 21:21
0

For the addItem() Just like @françois-huppé mentioned, you need to add an id to the input text.

function addItem() {
    originalArray.unshift(document.getElementById('new_element').value); 
    document.getElementById('new_element').value = ""; 
    disp(); 
 }

 function disp() {
   let str = "";
   for (let i = 0; i < originalArray.length; i++) { 
      str += `<li>${originalArray[i]}</li>`;
    }

  document.getElementById('firsttree').innerHTML = str;
}

On the disp() function, there are two things to note.

  1. Since you are appending each value to an Ordered List <ol>, you don't need a line break <br> because <li> has a display-block property by default which will display each item on a new line.

  2. You also do not need to number the items str += i + ". "+ originalArray[i] the ordered-list will number it.

You can check the working solution here https://codepen.io/sirwhite/pen/mddKxqr

Afia
  • 683
  • 5
  • 17