Javascript 根据javascript中的索引将数组拆分为两个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6872630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:34:43  来源:igfitidea点击:

split an array into two based on a index in javascript

javascriptarrayssplit

提问by user811433

I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.

我有一个包含对象列表的数组。我想在一个特定的索引处拆分这个数组,比如说 4(这实际上是一个变量)。我想将拆分数组的第二部分存储到另一个数组中。可能很简单,但我想不出一个很好的方法来做到这一点。

回答by TJHeuvel

Use slice, as such:

使用slice,如下所示:

var ar = [1,2,3,4,5,6];

var p1 = ar.slice(0,4);
var p2 = ar.slice(4);

回答by Mark Amery

You can use Array@spliceto chop all elements after a specified index off the end of the array and return them:

您可以使用Array@splice在数组末尾的指定索引之后截断所有元素并返回它们:

x = ["a", "b", "c", "d", "e", "f", "g"];
y = x.splice(3);
console.log(x); // ["a", "b", "c"]
console.log(y); // ["d", "e", "f", "g"]

回答by mamoo

use slice:

使用切片

var bigOne = [0,1,2,3,4,5,6];
var splittedOne = bigOne.slice(3 /*your Index*/);

回答by Mustkeem K

I would recommend to use slice() like below

我建议使用 slice() 如下所示

ar.slice(startIndex,length);or ar.slice(startIndex);

ar.slice(startIndex,length);或者 ar.slice(startIndex);

var ar = ["a","b","c","d","e","f","g"];

var p1 = ar.slice(0,3);
var p2 = ar.slice(3);

console.log(p1);
console.log(p2);

回答by masterspambot

You can also use underscore/lodash wrapper:

您还可以使用下划线/lodash 包装器:

var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);

回答by Micha? Wojas

Simple one function from lodash: const mainArr = [1,2,3,4,5,6,7] const [arr1, arr2] = _.chunk(mainArr, _.round(mainArr.length / 2));

来自 lodash 的一个简单函数: const mainArr = [1,2,3,4,5,6,7] const [arr1, arr2] = _.chunk(mainArr, _.round(mainArr.length / 2));