JavaScript:按顺序重新排列数组-最大,最小,第二大,第二小,第三大,第三小, [英] JavaScript: Rearrange an array in order – largest, smallest, 2nd largest, 2nd smallest, 3rd largest, 3rd smallest,

查看:46
本文介绍了JavaScript:按顺序重新排列数组-最大,最小,第二大,第二小,第三大,第三小,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数数组,其中的值应按以下顺序排序:如果我们有一个数组

Given an array of integers, where the values should be sorted in the following order: if we have an array

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

我们必须这样重新排列:最大数字,最小数字,第二大数字,第二小数字...

we must rearrange it this way: largest number, smallest number, 2nd largest number, 2nd smallest number, ...

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

我得到了第一个最大和最小的数字,但是无法弄清楚如何使它对于数组中的所有值都是动态的.

I get the first largest and smallest numbers, but can't figure out how to make it dynamic for all values in the array.

我知道我必须接受两个变量,例如 firstSmallest firstLargest 并将它们分别指向数组的第一个索引和最后一个索引,然后运行一个循环在下面的代码中进行操作,并通过递增 firstSmallest 并递减 firstLargest 将值存储到新数组中,但无法在代码中实现.

I know that I must take two variables, say firstSmallest and firstLargest and point them to the first and last index of the array respectively, run a loop, which I do already in the code below, and store value into new array by incrementing firstSmallest and decrementing firstLargest, but couldn't implement into code.

let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]

let output = [];

function meanderArray(unsorted){
  let sorted = unsorted.sort((a, b) => a-b);
  let firstSmallest = sorted[0];
  let firstLargest = sorted[unsorted.length-1];

  for(let i = 0; i <= sorted.length; i++){
  //I should increment firstSmallest and decrement firstLargest numbers and store in output
  } 
 return output;
}
meanderArray(unsortedArr);
console.log(output);

推荐答案

您可以使用一个切换对象,该对象从数组中获取第一项或最后一项的属性,并进行迭代,直到没有更多可用项为止.

You could take a toggle object which takes the property of either the first item or last from an array and iterate until no more items are available.

function meanderArray([...array]) {
    const 
        result = [],
        toggle = { shift: 'pop', pop: 'shift' };

    let fn = 'shift';

    array.sort((a, b) => a - b);

    while (array.length) result.push(array[fn = toggle[fn]]());

    return result;
}


console.log(...meanderArray([1, 5, 8, 7, 6, -1, -5, 4, 9, 5]));

这篇关于JavaScript:按顺序重新排列数组-最大,最小,第二大,第二小,第三大,第三小,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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