Sobes.tech
Junior

Ako zoradiť v poli iba nepárne čísla?

sobes.tech AI

Odpoveď od AI

  1. Filtrujte pole, pričom ostávajú iba nepárne čísla.
  2. Zoradiť získané pole nepárnych čísel.
  3. Prejsť pôvodné pole a nahradiť nepárne čísla zoradenými, pričom zachováte ich pôvodné pozície.
// Pôvodné pole
const arr = [5, 2, 8, 1, 4, 7, 6, 3, 9];

// Filtrácia a zoradenie nepárnych čísel
const oddSorted = arr.filter(num => num % 2 !== 0).sort((a, b) => a - b);

// Vytvorenie nového poľa nahradením nepárnych čísel zoradenými
let oddIndex = 0;
const sortedArr = arr.map(num => {
  if (num % 2 !== 0) {
    return oddSorted[oddIndex++];
  }
  return num;
});

// sortedArr bude [1, 2, 3, 8, 4, 5, 6, 7, 9]