Jump to content

javascript how to sort this condition trough objects ?


espace
 Share

Recommended Posts

Hi,

I have a specific question based on this case...

Assuming i have this objects

pig[0]

pig[1]

ball

if i check the distance on y  between ball and the pigs and if i want the biggest value trough the pigs and after do a specific action on the pig who have the biggest value ? i try with array.sort() but i can't find a solution to after identify the concerned pig...

Example :

ball.y  - pig[0].y = 54

ball.y - pig[1].y = 120

ok its pig[1] => do a specific action on it !

Thanks 

 

 

 

Edited by espace
Link to comment
Share on other sites

You only need the id of the pig with the biggest distance, so I'd loop through the pigs and store the id with the biggest y value:

 

let pigIDWithFurthestY;
let biggestDistance = 0;

for(let i = 0; i < pig.length; i++) {
    if(ball.y - pig[i].y > biggestDistance) {
        biggestDistance = ball.y - pig[i].y;
        pigIDWithFurthestY = i;
    }
}

//ok, so at the end pigIDWithFurthestY will contain the i value of the pig that is the furthest in y.
//To do an action on it, just call it with

// pig[pigIDWithFurthestY]

//the variable names are just for you to understand what's happening, but you can name them as you wish.

 

Edited by Danidre
Fixed the for loop.
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...