简体   繁体   中英

Javascript: Sorting Objects Challenge

I have a bit of a challenge. I am working on a physics application with javascript. The two main objects being used are

var force = new Object();
var torque = new Object();
with properties
force.magnitude = newArray();
force.lengthfromorigin = new Array();
force.count;
torque.lengthfromorigin= new Array();
torque.count;

now, I'd like to sort these two objects into an array based on their respective lengthfromorigins

Example: force.lengthfromorigin = [5,8] and torque.lengthfromorigin=[2,6] so their order in this newArray would be [ torque[0], force[0], torque[1], force[1] ]

My question is it possible to have an array of different objects sorted by their respective properties, and to then use this array in a function which will make decisions based on which object is at the index. Also will I need to have an id property in each respective object to identify if the object is a torque or force.

Example:

if(newArray[i] == torque)
    //do stuff
else
    //do other stuff.

Something like this perhaps?

Let me explain the algorithm:

  1. Create a new array let it be called A .
  2. For each objects in objects :

    2.1 Let the current object be called obj .

    2.2 Use map to generate a new array called tuples of [obj, num] tuples for each lengthFromOrigin numbers of obj .

    3.3 Push all items of tuples into A .

  3. Sort A on tuple[1] (which is the number) ascending.

var objects = [
        { type: 'force', lengthFromOrigin: [5, 8] },
        { type: 'torque', lengthFromOrigin: [2, 6] }
    ],
    sorted = objects.reduce(function (arr, obj) {
        arr.push.apply(arr, obj.lengthFromOrigin.map(function (num) {
            return [obj, num];
        }));

        return arr;           
    }, []).sort(function (a, b) {
        return a[1] - b[1];    
    });

console.log(sorted);

Then you can loop over sorted and easily identify if it's a torque or force by looking at the first element in the tuple.

sorted.forEach(function (tuple) {
    console.log(tuple[0].type, tuple[1]);
});

//torque 2
//force 5
//torque 6
//force 8 

The answer is Yes ,

But you have to identify each object before you access their properties. In your case Both of the objects have a common property called lengthfromorigin which can be used to sort them properly.

To identify each object you can use a property like ID or Name .

if(Mydata[i].Name = 'torque'){
  //your code goes here
}
else if(Mydata[i].Name = 'force'){
  //your code goes here
}

Hope this will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM