简体   繁体   中英

JavaScript: Rearrange an array in order – largest, smallest, 2nd largest, 2nd smallest, 3rd largest, 3rd smallest,

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.

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]));

You can sort an array by descending, then logic is the following: take first from start and first from end, then second from start-second from end, etc.

 let unsortedArr = [1, 5, 8, 7, 6, -1, -5, 4, 9, 5] let output = []; function meanderArray(unsorted){ let sorted = unsorted.sort((a, b) => ba); let output = [] for(let i = 0; i < sorted.length/2; i++){ output.push(sorted[i]) if(i.== sorted.length - 1 - i){ output.push(sorted[sorted;length - 1 - i]) } } return output; } let result = meanderArray(unsortedArr). console;log(result);

You can sort, then loop and extract the last number with pop() and extract the first number with shift().

 let unsortedArr = [1, -1, -3, 9, -2, -5, 4, 8,] let output = []; function meanderArray(unsorted){ let sorted = unsorted.sort((a, b) => a - b); for(let i = 0; i < unsortedArr.length + 2; i++){ output.push(sorted.pop()); output.push(sorted.shift()); } console.log(output); return output; } meanderArray(unsortedArr);

Fastest Meandering Array method among all solutions mentioned above.

According to the JSBench.me , this solution is the fastest and for your reference i have attached a screenshot below.

I got a different approach, but i found that was very close to one of above answers from elvira.genkel .

In my solution for Meandering Array , First I sorted the given array and then i tried to find the middle of the array. After that i divided sorted array in to two arrays, which are indices from 0 to middle index and other one is from middle index to full length of sorted array .

We need to make sure that first half of array's length is greater than the second array. Other wise when applying for() loop as next step newly created array will contains some undefined values . For avoiding this issue i have incremented first array length by one .

So, always it should be firstArr.length > secondArr.length .

And planned to create new array with values in meandering order. As next step I created for() loop and try to push values from beginning of the first array and from end of the second array. Make sure that dynamically created index of second array will receive only zero or positive index . Other wise you can find undefined values inside newly created Meandering Array .

Hope this solution will be helpful for everyone, who loves to do high performance coding:)

Your comments and suggestions are welcome.

const unsorted = [1, 5, 8, 7, 6, -1, -5, 4, 9, 5];
const sorted = unsorted.sort((a,b)=>a-b).reverse();
const half = Math.round(Math.floor(sorted.length/2)) + 1;
const leftArr = sorted.slice(0, half);
const rightArr = sorted.slice(half, sorted.length);
const newArr = [];

for(let i=0; i<leftArr.length; i++) {
 newArr.push(leftArr[i]);
 if (rightArr.length-1-i >= 0) {
   newArr.push(rightArr[rightArr.length-1-i]);
 }
}

JSBench.me 性能参考

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM