Reputation: 1725
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:
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.
Upvotes: 0
Views: 78
Reputation: 664766
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;
})
Upvotes: 1
Reputation:
if you say faces.sort (function (a,b).... then a already is an item of faces so why call faces[a]... its a.length
Upvotes: 0