简体   繁体   English

反转数组中的项目对

[英]Reverse pairs of items in array

Consider the array考虑数组

let myArray = [0,1,2,3,4,5,6,7]

I want to sort it this way我想这样排序

let reversedPairs = [myArray[6],myArray[7],myArray[4],myArray[5],myArray[2],myArray[3],myArray[0],myArray[1]]
// RESULT [6,7,4,5,2,3,0,1]

How can I achieve the RESULT without having to go through the array like in reversePairs ?如何在不需要reversePairs的情况下像 reversePairs 一样通过数组来实现 RESULT? I'm interested in sorting them by their indexes and not their values.我有兴趣按它们的索引而不是它们的值对它们进行排序。

Thank you.谢谢你。

if arr.length is an even number(array of pairs) than如果arr.length是偶数(数组对),则

 const arr = [0, 1, 2, 3, 4, 5, 6, 7] const reversePairs = arr => arr.map((_, i) => arr[arr.length - i - 2 * (1 - i % 2)]) console.log(reversePairs(arr))

You can iterate over the pairs, swap them, and reverse the resulting array in the end:您可以遍历这些对,交换它们,最后反转结果数组:

 let myArray = [0,1,2,3,4,5,6,7]; for(let i = 0; i < myArray.length-1; i+=2){ let temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; } myArray = myArray.reverse(); console.log(myArray);

You could take the integer half for the delta and sort the rest ascending.您可以将 integer 一半作为增量,然后对 rest 进行升序排序。

 let values = ['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i'], result = [...values.keys()].sort((a, b) => (b >> 1) - (a >> 1) || a - b) // or Math.floor(a / 2).map(i => values[i]); console.log(...result); // [6, 7, 4, 5, 2, 3, 0, 1]

This approach isn't the most efficient, but it is more readable.这种方法不是最有效的,但它更具可读性。 Basically we use reduce() to loop through each value and if the current index % 2 == 0 it is the first value of the pair, so we unshift a new array to the beginning.基本上我们使用reduce()循环遍历每个值,如果当前index % 2 == 0它是该对的第一个值,所以我们unshift一个新数组移到开头。 if index % 2 == 1 we add the value to the first array.如果index % 2 == 1我们将值添加到第一个数组。 Then we call flat() to combine the multiple pair arrays into one.然后我们调用flat()将多对 arrays 合并为一个。

It's not the most efficient because we have to loop through everything twice and create some intermediate arrays.这不是最有效的,因为我们必须遍历所有内容两次并创建一些中间 arrays。 If you're list of values is super large (thousands of values or more) I would use the method further down.如果您的值列表非常大(数千个或更多值),我会使用该方法进一步向下。 If not, I'd use this as it is easier to understand.如果没有,我会使用它,因为它更容易理解。

 const input = [0,1,2,3,4,5,6,7]; const output = input.reduce((result, value, index) => { index % 2 == 0? result.unshift([value]): result[0].push(value); return result; }, []).flat(); console.log(output);

This method gets it all done with one array in one loop:此方法在一个循环中使用一个数组完成所有操作:

 const input = [0,1,2,3,4,5,6,7]; const length = input.length; const output = input.reduce((result, value, index) => { const reversedIndex = length - index - 1; result[reversedIndex % 2 == 0? reversedIndex + 1: reversedIndex - 1] = value; return result; }, []); console.log(output);

In my opinion, it is a little harder to understand, but it works because the final array is going to be the same length, so we basically just get its reversed index, and then shift it up or down by one based on if it is the first or second value ( index % 2 == 0 or index % 2 == 1 ) in the pair.在我看来,这有点难以理解,但它是有效的,因为最终的数组将是相同的长度,所以我们基本上只是得到它的反向索引,然后根据它是否向上或向下移动它对中的第一个或第二个值( index % 2 == 0index % 2 == 1 )。

... straightforward and depended on an even number of array items... ...简单明了,取决于偶数个数组项...

 let myArray = [0, 1, 2, 3, 4, 5, 6, 7] function getReorderedArrayPairWiseFromRight(arr) { const itemCount = arr.length; let idx = itemCount; let list = []; while (list.length < itemCount) { idx = (idx - 2); list = list.concat(arr.slice(idx, (idx + 2))); } return list; } console.log(myArray); console.log(getReorderedArrayPairWiseFromRight(myArray));
 .as-console-wrapper { min-height: 100%;important: top; 0; }

... or based on Array.prototype.reduceRight and totally agnostic to any array's item count... ...或基于Array.prototype.reduceRight并且完全不知道任何数组的项目数...

 function collectPairWiseFromRight(collector, item, idx, arr) { if (((idx % 2) === 0) && (idx < (arr.length - 1))) { collector.push(arr[idx]); collector.push(arr[idx + 1]); } return collector; } console.log( [0, 1, 2, 3, 4, 5, 6, 7].reduceRight(collectPairWiseFromRight, []) ); console.log( [0, 1, 2, 3, 4, 5, 6, 7, 8].reduceRight(collectPairWiseFromRight, []) ); console.log( [0, 1, 2, 3, 4, 5, 6].reduceRight(collectPairWiseFromRight, []) ); console.log( [0, 1, 2, 3, 4, 5].reduceRight(collectPairWiseFromRight, []) ); console.log( [0, 1].reduceRight(collectPairWiseFromRight, []) ); console.log( [0].reduceRight(collectPairWiseFromRight, []) ); console.log( [].reduceRight(collectPairWiseFromRight, []) );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

Array can contain anything.. the order will be as you wanted it!数组可以包含任何内容.. 顺序将如您所愿!

let myArray = [0,1,2,3,4,5,6,7];
myArray.reverse();
let my2=myArray.map((num,index,myArray)=>
  (index%2===0?[]:[num,myArray[index-1]])
);
console.log(my2.flat());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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