0

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)

2
  • if it is always split into 3 arrays then this is fine i guess Commented Nov 12, 2022 at 13:25
  • There's no need to make a copy of the array and use it. slice returns a new array of elements each time. Commented Nov 12, 2022 at 13:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.