1

I have an array containing user inputs and I want to display the last five inputs from the array in HTML:

function display_last_five()
 {
   var e = "<hr/>";   
     e += array.slice(Math.max(array.length - 5, 0)) + " ";
   document.getElementById('Result').innerHTML = e;
}

What I get:

Input1,Input2,Input3

What I want:

Input1 Input2 Input3

In there a way to manipulate the output or is the input stored incorrect?

2
  • 3
    You're using the default toString implementation of an array; use join instead. Commented Sep 6, 2018 at 16:08
  • 1
    BTW, your title is a little odd considering the content of the question; you may want to edit it to talk about commas rather than quotation marks... Commented Sep 6, 2018 at 16:09

4 Answers 4

2

Using vanilla JavaScript :

function displayLastFive ( array )
{ 
  // Get the output element
  let result = document.getElementById( 'result' );
  
  // Show the last elements of the array, to a maximum of 5 elements
  result.innerHTML = `<hr/>${ array.slice( -5 ).join( ' ' ) }`;
}

displayLastFive( [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] );
<div id="result"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

I woul try using Array.join instead of string concatenation.

function display_last_five()
 {
   var e = "<hr/>";   
     e += array.slice(Math.max(array.length - 5, 0)).join(" ");
     document.getElementById('Result').innerHTML = e;
}

1 Comment

will try this now. looks much cleaner thank you
1

var array = ["input1","input2","input3","input4","input4","input5","input6","input7"];
var newHTML = [];
var count=0;
for (var i =array.length; i != 0; i--) {
  if(count==6) break
    newHTML.push(array[i]);
    count++
}
$(".element").html(newHTML.join(" "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element"></div>

Comments

0
 function display_last_five()
  {
    var e = "<hr/>";   
      e += array.slice(Math.max(array.length - 5, 0)) + " ";
    document.getElementById('Result').innerHTML = e.replace(/,/g, ' '))
 }

Use .replace() to remove all ',' and replace with a space

1 Comment

this works, thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.