Home > Software design >  Splitting an array into 3 unequal arrays in JavaScript
Splitting an array into 3 unequal arrays in JavaScript

Time:11-13

Suppose I have an array of

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

And I want to split it in 3, with two arrays containing the first and last X elements of the original array, and the third array containing the remaining elements, like so:

#1 - [0, 1, 2]
#2 - [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#3 - [13, 14, 15]

Is there a shorter/better way of doing that instead of:

const splitBy = 3;
const originalArray = Array.from(Array(16).keys());
const result = [
  originalArray.slice(0, splitBy),
  originalArray.slice(splitBy, -splitBy),
  originalArray.slice(-splitBy),
];

console.log(result)

CodePudding user response:

"better" is subjective... however, if you need this more than once, a generic function could be an option:

function multiSlice(a, ...slices) {
    let res = [], i = 0

    for (let s of slices) {
        res.push(a.slice(i, s))
        i = s
    }

    res.push(a.slice(i))
    return res
}

// for example,

const originalArray = Array.from(Array(16).keys());

console.log(multiSlice(originalArray, 3, -3))
console.log(multiSlice(originalArray, 2, 5, 10, 12))

  • Related