0

I have an array of small arrays. The small arrays are IDs to objects that belong together.

faces = [[0,1,2,3],[4,5,6,7],[0,3,7,4],[1,2,5,6],[0,1,5,4],[2,3,7,6]];

I want to sort the array faces based on a calculation of the values inside the smaller arrays. Each value represent a z-value.

The Setup:

  • I have an array of objects named objects.
  • Each object has an array of vectors named vectors.
  • Each vector has three coordinates: x,y,z.
  • Each object also has an array called faces.
  • Faces is an array of smaller array of IDs for the vectors. Each small array is a cluster of vectors.

What I want to do is to sort the array faces based on the average value of the z-value that are represented inside the small arrays.

I'm basing my try on this:

myArray.sort(function(a,b){
return b-a;
})

This is what I have so far in terms of sorting the objects[i].faces array:

objects[i].faces.sort(function(a,b){
    var value1=0;
    var value2=0;
    for (var j = 0; j<objects[i].faces[a].length; j++) {
        value1+=objects[i].vectors[faces[a][j]].z;
    }
    for (var j = 0; j<objects[i].faces[b].length; j++) {
        value2+=objects[i].vectors[faces[b][j]].z;
    }
return value1/objects[i].faces[a].length-value2/objects[i].faces[b].length;
})

It's currently complaining that he can't read the property "length" of undefined.

2
  • Can you include value of vectors as well as the expected output? Commented Feb 12, 2014 at 21:27
  • a and b already refer to an array in faces. Commented Feb 12, 2014 at 21:36

2 Answers 2

1

a and b are the to-be-compared items, not their indices. Use

var vectors = objects[i].vectors;
objects[i].faces.sort(function(a,b){
    var value1 = 0,
        value2 = 0;
    for (var j=0; j<a.length; j++)
        value1 += vectors[a[j]].z;
    for (var j=0; j<b.length; j++)
        value2 += vectors[b[j]].z;
    return value1/a.length - value2/b.length;
})
Sign up to request clarification or add additional context in comments.

1 Comment

It looks very obvious when you say it and it worked beautifully. Thank you!
0

if you say faces.sort (function (a,b).... then a already is an item of faces so why call faces[a]... its a.length

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.