JS array elements from small to large sorted instance code:
Sometimes you need to sort the numbers in the array, and here is an example of a code that sorts the numbers from small to large, hoping to help you.
The instance code is as follows:
vararr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98];varlen=Arr.length;console.log (Arr.join (","));varNewarr=[]; for(vari=0;i<len;i++) {Newarr.push (Math.min.apply (NULL, arr)); Arr.splice (R (arr,math.min.apply (NULL, arr)), 1);}//find the position of the minimum value in the arrayfunctionR (s,v) { for(kinchs) { if(s[k]==v) { returnK; }}}console.log (Newarr.join (","))
The above code to achieve the ordering requirements, the following brief introduction of its implementation process.
I. Principle of implementation:
The code is simple, and so is the principle. is to create a new array newarr, and then use Math.min.apply () to get the minimum value in the original array, put this value in a new array, and then delete the minimum value in the element, so that the Mong Loop, the implementation of this function, see the code comment.
two. Code comments:
1.var arr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98], create an array.
2.var Len=arr.length, assigns the length of the array to the variable len.
3.console.log (Arr.join ()), returns a string consisting of array elements separated by commas.
4.var newarr=[], create an empty array.
5.for (Var i=0;i<len;i++) {}, iterating through the elements in the array.
6.newarr.push (Math.min.apply (Null,arr)), put the smallest value in the array arr into the new array newarr.
7.arr.splice (R (arr,math.min.apply (Null,arr)), 1), removes the minimum value from the ARR array.
8.function R (s,v) {}, this function can return the index of the specified element in the array, the parameter s is an array, and the parameter V is a value in the array.
9.for (k in s) {}, iterating through the elements in the array.
10.if (s[k]==v) {return k;}, returns the index K if the value passed is equal to the value of the corresponding indexed array element.
11.console.log (Newarr.join (",")) outputs a new array element.
three. Related reading:
The 1.join () function can be found in theThe join () method of the JavaScript array objectA chapter.
The 2.push () function can be found in theThe push () method of the JavaScript array objectA chapter.
The 3.math.min () function can be found in theJavaScript's Math.min () methodA chapter.
The 4.apply () function can be found in thethe role and difference of the call () and apply () of JavaScriptA chapter.
The 5.splice () function can be found in theThe Splice () method of the JavaScript array objectA chapter.
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=9381
For more information, refer to: http://www.softwhy.com/javascript/
JS array elements from small to large sorted instance code