Recently encountered the need to insert a new object in an object array, and sorted by year, month descending order, if the direct push into the new object and then sort of, of course, here is another way to directly compare array elements, only a for loop and do not need to run full, time is less than or equal to O (n).
vararr = [{y:2014,m:10},{y:2014,m:7},{y:2014,m:1},{y:2013,m:7},{y:2013,m:1}];varNewarr = {Y:2013,m:10}; for(vari=0;i<arr.length;i++) {document.write ("y:" +arr[i].y + "M:" +arr[i].m+ "<br/>")}if(Arr[0].y < NEWARR.Y) {Arr.splice (0,0,newarr);}Elseif(Arr[arr.length-1].y > Newarr.y) {Arr.push (newarr);}Else{ for(vari=0;i<arr.length;i++){ if(Arr[i].y = =newarr.y) {if(ARR[I].M < NEWARR.M) {Arr.splice (I,0,newarr); Break;} Else if(ARR[I+1].M < NEWARR.M) {Arr.splice (I+1,0,newarr); Break;} }}}document.write ("<br><br>") for(vari=0;i<arr.length;i++) {document.write ("y:" +arr[i].y + "M:" +arr[i].m+ "<br/>")}</script></body>The second for loop is compared and inserted, and the other is a printed array.
Two-dimensional comparison and insertion of JavaScript object arrays