Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
Javascript: Element Width Based On Negative Values - From Lesser to Larger

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

    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>

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!