I have an array as :
let arrVals = [{img:'imgOne.jpg', num:-99},
{img:'imgOne.jpg', num:-500},
{img:'imgTwo.jpg', num:-20},
{img:'imgThree.jpg', num:-33},
{img:'imgFour.jpg', num:-44}
]
Now I loop through this and programmatically generate images from the array of objects inside:
<div id="imgContainer">
</div>
for (let i = 0; i < arrVals.length; i++) {
var img = document.createElement('img');
img.src = arrVals[i].img;
img.style.width = `${arrVals[i].num}px`;
// appendChild to imgContainer
}
I am using the negative values from the objects property, arrVals[i].num but I cannot just convert these to positive numbers and use them as a width value. I am trying to get positive numbers with the largest positive number corresponding to - say - (-30) and smallest - say - corresponding to (-55)
I need to use these values to apply styling width on their corresponding elements. I cannot just convert these values to positive numbers and use them as the one that is supposed to be the smallest (-500 in this example) in terms of width would have the largest width. The above array should corresponds to this results:
CSS Width from smallest to largest based on the array values:
> -500 should corresponds to the smallest width
> -99 width is larger than the width given to -500
> -44 width is larger than the width given to -99
> -33 width is larger than the width given to -44
> -20 should have the largest width given its value in the array
Any insights on how to achieve this would be much appreciated!
let arrVals = [{ img: 'imgOne.jpg', num: -99 },
{ img: 'imgOne.jpg', num: -500 },
{ img: 'imgTwo.jpg', num: -20 },
{ img: 'imgThree.jpg', num: -33 },
{ img: 'imgFour.jpg', num: -44 }
];
for (let i = 0; i < arrVals.length; i++) {
var img = document.createElement('img');
document.getElementById('imgContainer').appendChild(img);
img.src = arrVals[i].img;
img.style.width = `${Math.abs(arrVals[i].num)}px`;
}
<div id="imgContainer"></div>