Hyebin‘s blog
Published 2022. 1. 12. 15:05
[codewars/JS] Sort the odd Algorithm/Codewars

Task

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Examples

[7, 1]  =>  [1, 7]
[5, 8, 6, 3, 4]  =>  [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]  =>  [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]

<code>

function sortArray(array) {
  const result = array.filter((a)=>
     a%2 !== 0)
  result.sort(function(a,b){
    return a-b
  });
  console.log(result);
  let count = 0;
  const newarray = [];
  for(let i=0;i<array.length;i++){
    if(array[i]%2==0){
      newarray[i]=array[i];
    }
    if(array[i]%2!==0){
      newarray[i]=result[count];
      count++;
    }
    }console.log(newarray)
  return newarray
    
}

 

profile

Hyebin‘s blog

@hyebin Lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그