split an array into two based on a index in javascript

Viewed 98116

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.

7 Answers

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

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 })

Related