如何对升序排列的奇数数组进行排序,但将偶数保持在其位置? [英] How to sort an array of odd numbers in ascending order, but keep even numbers at their position?

查看:108
本文介绍了如何对升序排列的奇数数组进行排序,但将偶数保持在其位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想排序奇数而不移动偶数.例如,当我写 :

I want to sort only odd numbers without moving even numbers. For example, when I write :

sortArray([5, 3, 2, 8, 1, 4])

预期结果是:

[1, 3, 2, 8, 5, 4]

我是JavaScript的新手,我在互联网上遇到了一个使我感到困惑的挑战.我通常不会在Internet上发布寻求解决方案的信息,但是我已经尝试了几个小时,并且想在JavaScript中学习这个概念.

I am new to JavaScript and I came across a challenge on the Internet that has me perplexed. I normally wouldn't post asking for a solution on the Internet, BUT I have tried for hours and I would like to learn this concept in JavaScript.

挑战说明:

您有一个数字数组. 您的任务是对升序的奇数进行排序,但偶数必须在其位置. 零不是一个奇数,您不需要移动它.如果您有一个空数组,则需要将其返回.

You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

到目前为止,这是我的代码,请放心,我正处于编程的开始阶段.

Here is my code so far, please take it easy on me I am in the beginning stages of programming.

function sortArray(array) {
  let oddNums = [];
  for(let i = 0; i < array.length; i++) {
    if(array[i] % 2 !== 0) {
      oddNums.push(array[i]);
    }
  }
  oddNums = oddNums.sort((a,b)=> a-b);
  array.concat(oddNums);
  array = array.sort((a,b) => a-b);
  return array;
}

推荐答案

您可以将一个辅助数组用于奇数索引,将另一个辅助数组用于奇数,对它们进行排序,然后将其重新应用到原始数组的先前存储的索引中.

You could take a helper array for the odd indices and another for the odd numbers, sort them and apply them back on the previously stored indices of the original array.

var array = [5, 3, 2, 8, 1, 4],
    indices = [];

array
    .filter((v, i) => v % 2 && indices.push(i))
    .sort((a, b) => a - b)
    .forEach((v, i) => array[indices[i]] = v);

console.log(array);

这篇关于如何对升序排列的奇数数组进行排序,但将偶数保持在其位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆