简体   繁体   English

为什么我的数组没有按照将对象推入数组的方式排序?

[英]Why is my array not ordering in the manner in which I push the objects into the Array?

Okay I have a slight problem with a javascript array of objects the array would look something like this: 好的,我对对象的javascript数组有一个小问题,该数组看起来像这样:

var myArray = [
           {Month : 1, Count : 1000},
           {Month : 2, Count : 1000},
           {Month : 9, Count : 1000},
           {Month : 10, Count : 1000},
           {Month : 11, Count : 1000},
           {Month : 12, Count : 1000},
     ]; 

The problem I am having is that I am using this array of objects to display data to a graph. 我遇到的问题是我正在使用此对象数组将数据显示为图形。 For the life of me I have attempted every way that I can think of to reorder this array in the manner that I need. 对于我的一生,我尝试了各种可以想到的方式,以自己需要的方式对数组进行重新排序。 that need being something like this: 需要这样的事情:

________________________________________________
 09       10       11       12        1        2

because the graph is supposed to be showing 6 months of data in reverse order starting with the current month. 因为该图应该从当前月份开始以相反的顺序显示6个月的数据。 I have tried several things including this: 我已经尝试了几件事,包括:

   Code Updated Below:

The calling of the method and loading it with an array of objects: 方法的调用并使用对象数组加载它:

<script>

monthArray = [];
        monthArray.push({"Month" : 1,
            "Count" : 1252});
        monthArray.push({"Month" : 2,
            "Count" : 1252});
        monthArray.push({"Month" : 9,
            "Count" : 1252});
        monthArray.push({"Month" : 10,
            "Count" : 1252});
        monthArray.push({"Month" : 11,
            "Count" : 1252});
        monthArray.push({"Month" : 12,
            "Count" : 1252});

sTest(monthArray);
</script>

which gave me the same result all over again::: 这又给了我相同的结果:::

   Updated Below:

Right now I am doing this all in a regular html file for testing purposes. 现在,出于测试目的,我正在常规html文件中进行所有操作。 Is there no good way to do this, I would try another way but honestly I don't know of any other ways. 没有好的方法可以做到这一点,我会尝试另一种方法,但老实说我不知道​​其他任何方法。

For reference the second part of this code has to remain as it is unless someone knows a better way to load a json object into this form of data, basically it is just a mimicry of what I am doing to convert my json object so I can effectively rename the months and the data before loading them to the d3.js bar chart that I am using. 作为参考,该代码的第二部分必须保持原样,除非有人知道将json对象加载到这种形式的数据中的更好方法,基本上这只是我为转换json对象所做的模仿,因此我可以有效地重命名月份和数据,然后再将其加载到我正在使用的d3.js条形图中。

Thanks in advance. 提前致谢。

EDIT: 编辑:

I have recently tried editing the code to concatenate two arrays and display the concatenated array but still received the same result. 我最近尝试编辑代码来连接两个数组并显示连接的数组,但仍然收到相同的结果。 Here is the new Code: 这是新的代码:

<script>
var sTest = function(array) {

    var newArray = [];
    var newArray2 = [];
    var currentMonth = 2;
    var index = -1;

    //loop through the array to grab the index of the current date to set 
    //my starting and ending points for loading the new array
    for (i = 0; i < array.length; i++) {
        document.write(array[i].Month + "<br/>");
        if (array[i].Month === currentMonth) {
            index = i;
        }
    }

    //test the index of the current date
    document.write("The index of the current date is: " + index + "<br/>");

    //test the length just to be sure and avoid out of bounds errors
    document.write("The length of the current array is: " + array.length + "<br/>");

    //Get the data after the current month and load it to the array first
    for (j = index + 1; j < array.length; j++) {
        newArray.push({"Month" : array[j].Month, "Count" : array[j].Count});
    }    

    //get the data up to the current month and load it into the new array last
    for (k = 0; k <= index; k++) {
        newArray2.push({"Month" : array[k].Month, "Count" : array[k].Count});
    }

    var finalArray = newArray.concat(newArray2);

    //test the printout of the new array to examine the results
    for (i = 0; i < finalArray.length; i++) {
        document.write("Month: " + array[i].Month + " Count: " + array[i].Count + "<br/>");
    }

};
</script>

And here is the same result: 这是相同的结果:

1
2
9
10
11
12
The index of the current date is: 1
The length of the current array is: 6

Month: 1 Count: 1252
Month: 2 Count: 1252
Month: 9 Count: 1252
Month: 10 Count: 1252
Month: 11 Count: 1252
Month: 12 Count: 1252

If you can change a little bit the array, here is one solution: 如果可以稍微改变一下数组,这是一种解决方案:

  1. Add a new parameter in the object called Order. 在名为Order的对象中添加一个新参数。
  2. "Fix" the month and assign it to the order (as the current month will be the last one, any month with a higher value is from the previous year, reduce its value by 12). “固定”月份并将其分配给订单(由于当前月份将是最后一个月份,任何值较高的月份都来自上一年,则将其值减少12)。
  3. Sort the array by the new Order value. 按新的Order值对数组进行排序。

The code would be like this: 代码如下:

var date = new Date();
var currentMonth = date.getMonth()+1; // months go from 0 to 11, but your code is 1-12

// add the new ordering parameter
for (var x = 0; x < myArray.length; x++) {
    if (myArray[x].Month > currentMonth) {
        myArray[x].Order = myArray[x].Month - 12;
    } else {
        myArray[x].Order = myArray[x].Month;
    }
}

// sort the array using the new Order value
myArray.sort(function compare(a,b) {
              if (a.Order < b.Order)
                 return -1;
              else
                 return 1;
            });

You can see it working here: http://jsfiddle.net/ypp9kc9y/ 您可以在这里看到它的工作原理: http : //jsfiddle.net/ypp9kc9y/


And here a "cleaner" solution that merges all of that into the compare function, and doesn't need additional variables: 这里是一个“更清洁”的解决方案,它将所有这些合并到compare函数中,并且不需要其他变量:

// sort the array using the new Order value
myArray.sort(function compare(a,b) {
          var date = new Date();
          var orderA = a.Month > date.getMonth()+1 ? a.Month -12 : a.Month;
          var orderB = b.Month > date.getMonth()+1 ? b.Month -12 : b.Month;
          if (orderA < orderB)
             return -1;
          else
             return 1;
        });

See it working here: http://jsfiddle.net/ypp9kc9y/1/ 看到它在这里工作: http : //jsfiddle.net/ypp9kc9y/1/

Your problem is right here: 您的问题就在这里:

//test the printout of the new array to examine the results
for (i = 0; i < finalArray.length; i++) {
    document.write("Month: " + array[i].Month + " Count: " + array[i].Count + "<br/>");
}

You are looping through finalArray.length but your document.write is using array[i] not newArray[i] — you are looping over the original unmodified array. 您正在遍历finalArray.length但是document.write使用的是array[i] 而不是 newArray[i] -您正在遍历原始未修改的数组。

Check out the properties of the date object in JavaScript. 在JavaScript中检出date对象的属性。 If you use date math, rather than integer math, then 1/15 will come after 12/14. 如果使用日期数学而不是整数数学,则1/15将在12/14之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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