I have the following array, containing smaller arrays:
var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];
I would like to display them like this, removing the comma inside the smaller arrays and adding a hyphen:
Bananas - 2
Apples - 4
Oranges - 5
I have tried the following, however it's still not working:
var fruits = [
["Bananas", "2"],
["Apples", "4"],
["Oranges", "5"]
];
var fruitsToday = [];
for (i = 0; i < fruits.length; i++) {
fruitsToday += fruits[i].join(" - ");
}
document.getElementById("today").innerHTML = fruitsToday.join("<br>");
Any assistance would be greatly appreciated!
Edit to add additional explanation and reading:
Implicit coercion is triggered by the binary + operator, when any operand is a string
You need to use an array and push to it. Using the + operator will coerce the array into a string and concatenate the strings.
var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];
var fruitsToday = [];
for (i=0; i < fruits.length; i++) {
fruitsToday.push(fruits[i].join(" - "));
}
document.getElementById("today").innerHTML = fruitsToday.join("<br>");
<div id="today"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With