Two-dimensional comparison and insertion of JavaScript object arrays

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.