[05.01.22] Coding test

Juyeon.it·2022년 5월 1일
0

Coding test

목록 보기
20/32

Sort the odd

Description

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]

My answer

function sortArray(array) {
  const hideOdds = array.map((e) => e % 2 === 0 ? e : "");
  const odd = array.filter((e) => e % 2 !== 0).sort((a, b) => a - b);
  const result = [];
  
  for (let i = 0, oddIndex = 0; i < array.length; i += 1) {
    if (hideOdds[i] === '') {
      result.push(odd[oddIndex]);
      oddIndex++;
    } else {
      result.push(hideOdds[i])
    }
  }
  
  return result;
}

Other solutions

function sortArray(array) {
  const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
  return array.map((x) => x % 2 ? odd.shift() : x);
}

Wrap up

shift method

The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.
shift is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

array.shift()

return value

The removed element from the array; undefined if the array is empty.

source: mdn web docs

0개의 댓글

관련 채용 정보