开发者

split an array into two based on a index in javascript

开发者 https://www.devze.com 2023-03-23 23:52 出处:网络
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开发

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开发者_JAVA技巧. Might be simple, but I am unable to think of a nice way to do this.


Use slice, as such:

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

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


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

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"]


use slice:

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


I would recommend to use slice() like below

ar.slice(startIndex,length); or 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);


const splitAt = (i, arr) => {
  const clonedArray = [...arr];
  return [clonedArray.splice(0, i), clonedArray];
}

const [left, right] = splitAt(1, [1,2,3,4])

console.log(left) // [1]
console.log(right) // [2,3,4]


const [left1, right1] = splitAt(-1, [1,2,3,4])

console.log(left1) // []
console.log(right1) // [1,2,3,4]


const [left2, right2] = splitAt(5, [1,2,3,4])

console.log(left1) // [1,2,3,4]
console.log(right1) // []

Some benefits compared to other solutions:

  1. You can get the result with a one liner
  2. When split index is underflow or overflow, the result is still correct. slice will not behave correctly.
  3. It does not mutate the original array. Some splice based solutions did.
  4. There is only 1 splice operation, rather than 2 slice operations. But you need to benchmark to see if there is actual performance difference.


You can also use underscore/lodash wrapper:

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


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


const splitArrayByIndex = (arr, index) => {
  if (index > 0 && index < arr.length) {
    return [arr.slice(0, index), arr.slice(-1 * (arr.length - index))]
  }
}

const input = ['a', 'x', 'c', 'r']
const output = splitArrayByIndex(input, 2)

console.log({ input, output })

0

精彩评论

暂无评论...
验证码 换一张
取 消