Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove commas from arrays located inside an array

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!

like image 495
oak99 Avatar asked May 22 '26 05:05

oak99


1 Answers

Edit to add additional explanation and reading:

  • https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/
  • https://dev.to/promhize/what-you-need-to-know-about-javascripts-implicit-coercion-e23
  • https://www.ecma-international.org/ecma-262/6.0/#sec-type-conversion
    (ecma's table is the most accurate and concise to read, but its presentation may be a bit spartan to read. I'll be honest I'm not satisfied with the bloggers' overly verbose explanations of implicit coercion either.)

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>
like image 94
user120242 Avatar answered May 23 '26 17:05

user120242



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!