Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  132] [ 3]  / answers: 1 / hits: 44424  / 8 Years ago, tue, july 12, 2016, 12:00:00

I am new to JavaScript, and I have an array which contains numbers.


 var arr = [2,4,8,1,5,9,3,7,6];

How can I sort it using a native for loop in JavaScript?


I know sort function is available, but I want it through for loop.


The output should be:


 var res = [1,2,3,4,5,6,7,8,9];

More From » arrays

 Answers
29

I would do something like this...




var input = [2,3,8,1,4,5,9,7,6];

var output = [];
var inserted;

for (var i = 0, ii = input.length ; i < ii ; i++){
inserted = false;
for (var j = 0, jj = output.length ; j < jj ; j++){
if (input[i] < output[j]){
inserted = true;
output.splice(j, 0, input[i]);
break;
}
}

if (!inserted)
output.push(input[i])
}

console.log(output);




Maybe there are more efficient ways, but if you want to use the for loop, it's my first idea...


[#61408] Sunday, July 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonathoncamrynv

Total Points: 339
Total Questions: 98
Total Answers: 98

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
;