1
const liArray = [5.6, 8.7, 1.3, 10, 56];

const parentElement = document.getElementById("myDiv");

liArray.forEach((currentValue, index) => {
  var elm = document.createElement('p');
  elm.innerHTML = `${index + 1}. ${currentValue}`;
  parentElement.appendChild(elm);
});

<div id="myDiv"></div>

i have this code that creates a new paragraph element for every item in the array so the result will be :

1. 5.6
2. 8.7
3. 1.3
4. 10
5. 56

but i want to automaticaly add round bracket () to the lowest and highest number when creating the elements so the created elements will be like this

1. 5.6
2. 8.7
3. (1.3)
4. 10
5. (56)

how can i do this?

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26

2 Answers2

1

You can use Math.min() and Math.max() to get the lowest and highest values in the array. When you then loop through the array to output to the UI you can add the parentheses if the item in the iteration matches one of those values. Try this:

const liArray = [5.6, 8.7, 1.3, 10, 56];
const min = Math.min.apply(Math, liArray);
const max = Math.max.apply(Math, liArray);
const parentElement = document.getElementById("myDiv");

liArray.forEach((currentValue, index) => {
  var elm = document.createElement('p');
  let text = `${index + 1}. ${(currentValue == min || currentValue == max) ? `(${currentValue})` : currentValue}`;
  elm.innerText = text;
  parentElement.appendChild(elm);
});
<div id="myDiv"></div>

As an aside you can use an ol with li elements in order for HTML to generate a numbered list for you without having to track the index yourself.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    ahh yes i forgot that i can use ```ol``` xD, thanks for answering :D – I_love_vegetables Apr 23 '21 at 09:38
  • hi btw i have another doubt here, if there are 2 same numbers and they are both the highest/lowest number, it add parentheses to both the numbers, how can make it so that it only adds parentheses to one of them – I_love_vegetables Apr 27 '21 at 08:37
1

You can use Math.min and Math.max to find out the array limits. apply simply means you can pass in an array to those methods instead of a delimited list of numbers.

const liArray = [5.6, 8.7, 1.3, 10, 56];

const min = Math.min.apply(Math, liArray);
const max = Math.max.apply(Math, liArray);

console.log(min, max)

const parentElement = document.getElementById("myDiv");

liArray.forEach((currentValue, index) => {
  var elm = document.createElement('p');
  if (currentValue === min || currentValue === max) {
    elm.innerHTML = `${index + 1}. (${currentValue})`;
  } else {
    elm.innerHTML = `${index + 1}. ${currentValue}`;
  }
  parentElement.appendChild(elm);
});
<div id="myDiv"></div>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • hi btw i have another doubt here, if there are 2 same numbers and they are both the highest/lowest number, it add parentheses to both the numbers, how can make it so that it only adds parentheses to one of them – I_love_vegetables Apr 27 '21 at 08:37