Sorting arrays using for loop in Javascript

前端 未结 6 1031
灰色年华
灰色年华 2021-01-15 16:36

Is it possible to sort arrays in ascending/descending order using the for loop JavaScript?

I\'ve been learning JS going through a few practice quest

6条回答
  •  醉梦人生
    2021-01-15 16:54

    this for A to B

    function smallTobig(numbers) {
    
    let A_B = []
        for(let i = 0; i < numbers.length; i++) {
         for(let j = i; j < numbers.length; j++) {
            if (numbers[i] > numbers[j]) {
                let temp = numbers[i];
                numbers[i] = numbers[j];
                numbers[j] = temp;
            }
        }
        A_B.push(numbers[i])
    }
    return A_B
    }
    console.log(smallTobig([5, 2, 1, 4])); 
    console.log(smallTobig([999, 5, 0, 1, 4, 998])); 
    console.log(smallTobig([15, 32, 11, 14]));
    console.log(smallTobig([5, 4, 3, 2, 1, 0]));
    console.log(smallTobig([123, 321, 143, 313]));
    

    this for B to A

    function bigTosmall(numbers) {
    
    let B_A = []
        for(let i = 0; i < numbers.length; i++) {
         for(let j = i; j < numbers.length; j++) {
            if (numbers[i] < numbers[j]) {
                let temp = numbers[i];
                numbers[i] = numbers[j];
                numbers[j] = temp;
            }
        }
        B_A.push(numbers[i])
    }
    return B_A
    }
    console.log(bigTosmall([5, 2, 1, 4])); 
    console.log(bigTosmall([999, 5, 0, 1, 4, 998])); 
    console.log(bigTosmall([15, 32, 11, 14]));
    console.log(bigTosmall([5, 4, 3, 2, 1, 0]));
    console.log(bigTosmall([123, 321, 143, 313]));
    

提交回复
热议问题