无论大小,将阵列拼成两半?

时间:2021-12-13 02:12:32

I have an array I would like to split in half. So I can position the first half on the right side and the second half on the left side.

我有一个阵列,我想分成两半。所以我可以将前半部分放在右侧,将后半部分放在左侧。

I have used the splice function before:

我之前使用过拼接功能:

var leftSide = arrayName.splice(0,2);

But not sure how to splice it in half no matter the size, because the array will change in size dynamically.

但不确定无论大小如何将其拼接成一半,因为数组的大小会动态变化。

6 个解决方案

#1


41  

var half_length = Math.ceil(arrayName.length / 2);    

var leftSide = arrayName.splice(0,half_length);

edited the code following @Lightness Races in Orbit comment

编辑了Orbit评论中@Lightness Races之后的代码

#2


15  

You can simply refer to the array's length:

您可以简单地引用数组的长度:

var leftSide = arrayName.splice(0, Math.floor(arrayName.length / 2));

Since .splice() actually removes elements from the source array, the remaining elements in the array will be the elements for the right half.

由于.splice()实际上从源数组中删除了元素,因此数组中的其余元素将是右半部分的元素。

Math.floor() will round down to give the left side one less than the right side for odd lengths. You could use Math.ceil() if you want to round up to give the left side one more than the right side when the length is odd.

对于奇数长度,Math.floor()将向下舍入以使左侧小于右侧。你可以使用Math.ceil(),如果你想要向上舍入,当长度为奇数时,左侧比右侧更多。

#3


6  

Avoid Mutations

If you need to avoid mutations, for example if you have to split an array in react you don't want to mutate the original or it could lead to some very strange behaviour in your app.

如果您需要避免突变,例如,如果您必须拆分数组,您不想改变原始数据,或者它可能会导致您的应用程序中出现一些非常奇怪的行为。

Use Slice

You can get around this by using slice instead of splice

你可以通过使用切片而不是拼接来解决这个问题

Example

let yourArray = props.someArray;
let halfWayThough = Math.floor(yourArray.length / 2)

let arrayFirstHalf = yourArray.slice(0, halfWayThough);
let arraySecondHalf = yourArray.slice(halfWayThough, yourArray.length);

#4


1  

let leftSide = myArray.splice(0, Math.ceil(myArray.length / 2));
//The right side is stored in "myArray"

For example:

例如:

let letters = ['a', 'b', 'c', 'd', 'e'];
let leftSide = letters.splice(0, Math.ceil(letters.length /2));
let rightSide = letters;
console.log(leftSide);
=> ['a', 'b', 'c']
console.log(rightSide);
=> ['d', 'e']

More information: splice in the MDN docs

更多信息:拼接MDN文档


Note that this modifies your original array. If you want to keep the original array, clone the array, then use splice on the cloned array. From an SO question about cloning arrays:

请注意,这会修改您的原始数组。如果要保留原始数组,请克隆该数组,然后在克隆数组上使用splice。从一个关于克隆数组的问题:

There has been a huuuge BENCHMARKS thread, providing following information:

有一个huuuge BENCHMARKS线程,提供以下信息:

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

    对于闪烁浏览器,slice()是最快的方法,concat()有点慢,而while循环慢2.4倍。

  • for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.

    对于其他浏览器而while循环是最快的方法,因为这些浏览器没有slice和concat的内部优化。

//Fastest for Blink browsers (Opera/Chromium):
let clonedArray = originalArray.slice();
//For other browsers:
let clonedArray = [];
var i = myArray.length;
while (i--) clonedArray[i] = myArray[i];

#5


1  

This is a fun function for Avoiding Mutations with options:

这是一个有趣的功能,用于避免变异与选项:

function splitArray({ alternate, array }) {
  const halfIndex = Math.ceil(array.length / 2) - 1;
  let firstArray = true;
  return array.reduce((res, item, index) => {
    if (firstArray) {
      res[0].push(item);
      if (alternate || index >= halfIndex) {
        firstArray = false;
      }
    } else {
      res[1].push(item);
      if (alternate) {
        firstArray = true;
      }
    }
    return res;
  }, [[], []]);
}

And you can call it with an alternating option:

您可以使用交替选项调用它:

const myArray = [1,2,3,4,5,6,7,8];
const splitAlternate = splitArray({ alternate: true, array: myArray });
const splitNoAlternate = splitArray({ alternate: false, array: myArray });

console.log(myArray);
console.log(splitAlternate);
console.log(splitNoAlternate);

#6


0  

if you want the size of the array to stay equal you just need to alternate which array you write to (eg, alternate .push calls on the arrays).. Why don't you just create 2 arrays up front?

如果你希望数组的大小保持相等,你只需要替换你写入的数组(例如,在数组上交替使用.push调用)。为什么不直接创建2个数组呢?

var lelftHalf = yourArray.splice(0,arrayName.length / 2);

After you do that if you want to keep the 2 arrays the same size alternate between

执行此操作后,如果要保持2个阵列之间的大小相同

leftHalf.push(newElement);

and

yourArray.push(newElement1);

#1


41  

var half_length = Math.ceil(arrayName.length / 2);    

var leftSide = arrayName.splice(0,half_length);

edited the code following @Lightness Races in Orbit comment

编辑了Orbit评论中@Lightness Races之后的代码

#2


15  

You can simply refer to the array's length:

您可以简单地引用数组的长度:

var leftSide = arrayName.splice(0, Math.floor(arrayName.length / 2));

Since .splice() actually removes elements from the source array, the remaining elements in the array will be the elements for the right half.

由于.splice()实际上从源数组中删除了元素,因此数组中的其余元素将是右半部分的元素。

Math.floor() will round down to give the left side one less than the right side for odd lengths. You could use Math.ceil() if you want to round up to give the left side one more than the right side when the length is odd.

对于奇数长度,Math.floor()将向下舍入以使左侧小于右侧。你可以使用Math.ceil(),如果你想要向上舍入,当长度为奇数时,左侧比右侧更多。

#3


6  

Avoid Mutations

If you need to avoid mutations, for example if you have to split an array in react you don't want to mutate the original or it could lead to some very strange behaviour in your app.

如果您需要避免突变,例如,如果您必须拆分数组,您不想改变原始数据,或者它可能会导致您的应用程序中出现一些非常奇怪的行为。

Use Slice

You can get around this by using slice instead of splice

你可以通过使用切片而不是拼接来解决这个问题

Example

let yourArray = props.someArray;
let halfWayThough = Math.floor(yourArray.length / 2)

let arrayFirstHalf = yourArray.slice(0, halfWayThough);
let arraySecondHalf = yourArray.slice(halfWayThough, yourArray.length);

#4


1  

let leftSide = myArray.splice(0, Math.ceil(myArray.length / 2));
//The right side is stored in "myArray"

For example:

例如:

let letters = ['a', 'b', 'c', 'd', 'e'];
let leftSide = letters.splice(0, Math.ceil(letters.length /2));
let rightSide = letters;
console.log(leftSide);
=> ['a', 'b', 'c']
console.log(rightSide);
=> ['d', 'e']

More information: splice in the MDN docs

更多信息:拼接MDN文档


Note that this modifies your original array. If you want to keep the original array, clone the array, then use splice on the cloned array. From an SO question about cloning arrays:

请注意,这会修改您的原始数组。如果要保留原始数组,请克隆该数组,然后在克隆数组上使用splice。从一个关于克隆数组的问题:

There has been a huuuge BENCHMARKS thread, providing following information:

有一个huuuge BENCHMARKS线程,提供以下信息:

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

    对于闪烁浏览器,slice()是最快的方法,concat()有点慢,而while循环慢2.4倍。

  • for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.

    对于其他浏览器而while循环是最快的方法,因为这些浏览器没有slice和concat的内部优化。

//Fastest for Blink browsers (Opera/Chromium):
let clonedArray = originalArray.slice();
//For other browsers:
let clonedArray = [];
var i = myArray.length;
while (i--) clonedArray[i] = myArray[i];

#5


1  

This is a fun function for Avoiding Mutations with options:

这是一个有趣的功能,用于避免变异与选项:

function splitArray({ alternate, array }) {
  const halfIndex = Math.ceil(array.length / 2) - 1;
  let firstArray = true;
  return array.reduce((res, item, index) => {
    if (firstArray) {
      res[0].push(item);
      if (alternate || index >= halfIndex) {
        firstArray = false;
      }
    } else {
      res[1].push(item);
      if (alternate) {
        firstArray = true;
      }
    }
    return res;
  }, [[], []]);
}

And you can call it with an alternating option:

您可以使用交替选项调用它:

const myArray = [1,2,3,4,5,6,7,8];
const splitAlternate = splitArray({ alternate: true, array: myArray });
const splitNoAlternate = splitArray({ alternate: false, array: myArray });

console.log(myArray);
console.log(splitAlternate);
console.log(splitNoAlternate);

#6


0  

if you want the size of the array to stay equal you just need to alternate which array you write to (eg, alternate .push calls on the arrays).. Why don't you just create 2 arrays up front?

如果你希望数组的大小保持相等,你只需要替换你写入的数组(例如,在数组上交替使用.push调用)。为什么不直接创建2个数组呢?

var lelftHalf = yourArray.splice(0,arrayName.length / 2);

After you do that if you want to keep the 2 arrays the same size alternate between

执行此操作后,如果要保持2个阵列之间的大小相同

leftHalf.push(newElement);

and

yourArray.push(newElement1);