1

For example:

From

[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. 
x1 compares itself to x0, x2 and x3. And so on...

To

[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. 
x1 compares itself to x2 and x3 only. 
x2 only compares itself to x3. 
x3 does not need to do any comparison at all.

Essentially I'm looking to traverse an array one way only, with every element behind the current element ignored.

for (var i = 0; i < boids.length; i++) { 
//boids is an array containing elements "boid"


     var d = distSquared(this.position.x, this.position.y, boids[i].position.x, boids[i].position.y); 
       //get distance between current boid and all other boids in array. 
       //Looking to change this to get distance between current boid and all other boids infront of this element in the array.

     if (boids[i] == this) { //if the boid being compared is to its own self, skip it.
            continue;
        }
}

How would I go about implementing such a structure?

2
  • Welcome to SO! Just a pointer, I just see 1 for loop. Can you share how comparison is done. Commented Sep 24, 2016 at 7:07
  • so even this will be there in boids array. So just search index of this in array and initialise i accordingly. Commented Sep 24, 2016 at 7:54

4 Answers 4

1

What you are looking for is something like this:

var a = [1,2,3,4];

for(var i=0; i<a.length; i++){
  for(var j=i+1; j<a.length; j++){
    console.log(i,j)
  }
}

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.prototype.filter() to exclude an element or elements from an array

var arr = [1,2,3,4,5];
for (var i = 0; i < arr.length; i++) {
  var curr = arr[i];
  var not = arr.filter(function(_, index) {
    return index != i
  });
  console.log(`curr:${curr}`);
  not.forEach(function(el) {
    console.log(`${curr} is not ${el}`)
  })
}

1 Comment

Thanks for the reply, but I'm not looking to remove the currently check element in the list, but rather all elements behind it. Essentially I'm looking to traverse an array one way only.
0

You might do like this. Shaping up how to compare is up to you.

var arr = [1,2,3,4,5],
 result = arr.map((e,i,a) => a.slice(i+1).map(n => e-n));
console.log(result);

Comments

0

I used Array.prototype.indexOf() to solved my issue.

var j = boids.indexOf(this);
//get index of current element i array.

if (j < boids.length) {
    // if the index is lower than the overall length of the array (e.g. check traverse the array to elements infront of the current element, ignoring those behind)

    //Perform calculations here

   j++; //increment j

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.