Reputation: 3198
I have a string array where I need to display from 2nd item onwards. But within each item I need to further display from 2nd item. Say
I have an array
function myFunction() {
var fruits = ["BBanana", "BOrange", "TLemon", "TApple", "YMango"];
var citrus = fruits.slice(1).join("<br/>"); //skip first item
document.getElementById("demo").innerHTML = citrus;
}
The expected output is
Orange
Lemon
Apple
Mango
Instead
BOrange
TLemon
TApple
YMango
How do i achieve using improved performance?
Upvotes: 1
Views: 54
Reputation: 11
You can use reduce function, it will be less code than in other cases
function myFunction() {
const fruits = ["BBanana", "BOrange", "TLemon", "TApple", "YMango"];
const temp = fruits.slice(1).reduce( (ac, item) => ac + `${item.slice(1)}<br/>`, '')
document.getElementById("demo").innerHTML = temp;
}
Upvotes: 1
Reputation: 705
var fruits = ["BBanana", "BOrange", "TLemon", "TApple", "YMango"];
for(var i = 1; i < fruits.length; i++){
console.log(fruits[i].slice(1));
};
Upvotes: 1
Reputation: 191966
After you slice off the 1st item, use Array#map to create a list of item without the 1st letter using String#substring, then join:
Map and then join:
function myFunction() {
var fruits = ["BBanana", "BOrange", "TLemon", "TApple", "YMango"];
var citrus = fruits.slice(1)
.map(function(str) {
return str.substring(1);
})
.join("<br/>");
demo.innerHTML = citrus;
}
myFunction();
<div id="demo"></div>
Upvotes: 3