JavaScript arrays do not have a split() method: split() is for strings and creates an array from a string. To divide an existing array, use methods such as slice() or filter(); to remove or replace items in place, use splice().
What “split” means in JavaScript
The word “split” can describe several different operations. A string can be split at a delimiter, such as a comma, to produce an array of parts. An array can be divided into smaller arrays, filtered into groups, or have a section removed. JavaScript uses different methods for these jobs rather than one universal array method called split().
For example, calling items.split(',') fails if items is an array, because arrays do not define that method. The error is commonly a “split is not a function” TypeError. First identify the value’s type and the desired result:
- Use
string.split(separator)to turn text into an array of strings. - Use
array.splice()to remove, insert, or replace array elements while changing the original array. - Use
array.slice()to copy a range of elements without changing the original. - Use
filter()or a loop to divide items according to a condition.
Use splice to remove or replace array elements
splice() is probably the array method people are looking for when they say “split an array.” Its basic form is array.splice(start, deleteCount, item1, item2, ...). It starts at an index, removes up to deleteCount elements, and inserts any additional items at that position. It changes the array it is called on and returns a new array containing the removed elements.
const colors = ['red', 'green', 'blue', 'gold'];
const removed = colors.splice(1, 2);
console.log(removed); // ['green', 'blue']
console.log(colors); // ['red', 'gold']
Here, start is index 1 and deleteCount is 2, so two items are removed. The returned value is not the remaining array; it is the removed portion. This distinction matters when assigning the result: const rest = colors.splice(...) does not make rest the leftover items.
To insert without removing anything, set deleteCount to zero. To replace a single item, remove one and provide a replacement:
const scores = [10, 20, 30];
scores.splice(1, 0, 15); // inserts 15 at index 1
// scores is [10, 15, 20, 30]
scores.splice(2, 1, 25); // replaces 20 with 25
// scores is [10, 15, 25, 30]
Divide an array into two parts with slice
If you want two sections but need to preserve the original array, use slice(). It returns a shallow copy of the selected range and does not modify the source. The first argument is the start index; the optional second argument is the end index, which is excluded.
const letters = ['a', 'b', 'c', 'd', 'e'];
const left = letters.slice(0, 2);
const right = letters.slice(2);
console.log(left); // ['a', 'b']
console.log(right); // ['c', 'd', 'e']
console.log(letters); // ['a', 'b', 'c', 'd', 'e']
This approach is useful for dividing a list at a known position, such as splitting a page of results into a visible section and the remaining items. Because slice() makes a shallow copy, the arrays are separate but object values inside them are still shared references. Changing a property on an object in one result can therefore be seen through the same object in the other array.
Split a string into an array
When the input is text, split() is the right method. It belongs to strings, and its separator can be a literal string or a regular expression. For comma-separated text, for example:
const input = 'pear,plum,apple';
const fruits = input.split(',');
// fruits is ['pear', 'plum', 'apple']
A separator is not included in the resulting parts. A limit can restrict how many pieces are returned: 'a-b-c'.split('-', 2) produces ['a', 'b']. An empty separator has different behavior: 'cat'.split('') produces an array of characters. For some characters outside the basic multilingual plane, splitting this way can separate UTF-16 code units rather than user-perceived characters. If you need iteration by Unicode code point, Array.from(text) is often a better fit.
Splitting text on a regular expression can handle varying whitespace or delimiters. For instance, 'one two\tthree'.split(/\s+/) returns three words. If a regular expression contains capturing groups, captured values can also appear in the result, so avoid capturing parentheses when you only want to match separators.
Choose between splice, slice, and toSpliced
The main choice is whether the original array should change. Use splice() when mutation is intended, such as removing an item from a working list. Use slice() when you want a range as a separate array and want to leave the original untouched. These methods are not interchangeable: slice() does not insert or remove items, and splice() does not preserve the original.
Modern JavaScript also has toSpliced(), which returns a changed copy instead of mutating the receiver. It accepts the same kind of start, deletion count, and inserted items as splice():
const original = ['oak', 'pine', 'elm'];
const updated = original.toSpliced(1, 1, 'maple');
console.log(updated); // ['oak', 'maple', 'elm']
console.log(original); // ['oak', 'pine', 'elm']
toSpliced() is part of modern JavaScript, but older browsers or runtimes may not support it. Check the environments your project targets before relying on it, or use slice() and concatenation to build a copy. Also remember that declaring an array with const prevents reassignment of the variable; it does not prevent methods such as splice() from changing the array’s contents.
Divide an array by a condition or into chunks
When “split” means sorting items into groups based on a rule, filter() is a clear option. It creates a new array containing elements for which its callback returns true. Calling it with opposite conditions gives two groups:
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(number => number % 2 === 0);
const odd = numbers.filter(number => number % 2 !== 0);
// even is [2, 4, 6]; odd is [1, 3, 5]
Each call checks the array, so this is simple and readable for ordinary lists. If the condition is expensive or the array is very large, a single loop can place each item into the appropriate group in one pass. Choose the clearer approach unless profiling shows that performance needs attention.
To make fixed-size chunks, repeatedly take slices. This example creates groups of three and also handles a shorter final group:
function chunk(array, size) {
if (size <= 0) throw new RangeError('size must be positive');
const result = [];
for (let start = 0; start < array.length; start += size) {
result.push(array.slice(start, start + size));
}
return result;
}
chunk([1, 2, 3, 4, 5, 6, 7], 3);
// [[1, 2, 3], [4, 5, 6], [7]]
The function does not change the input array. Its validation also avoids an infinite loop: with a zero or negative chunk size, the loop would not advance correctly. For arrays containing objects, the chunks contain references to the same objects rather than deep copies.
Common mistakes and edge cases
- Using split on the wrong type: Check with
Array.isArray(value)when a variable may contain either text or an array. Convert intentionally rather than assuming the type. - Confusing the return value of splice: It returns removed items. The original array contains what remains after the operation.
- Forgetting the end index is excluded: With
slice(1, 3), indexes 1 and 2 are copied, not index 3. - Leaving out deleteCount:
array.splice(start)removes everything from that index to the end. Usearray.splice(start, 0, item)to insert without deleting. - Using a separator that does not match: If the separator is absent from a string,
split()usually returns a one-element array containing the original text. Whitespace around tokens may remain unless the input or separator accounts for it.
For negative indexes, slice() and splice() count backward from the end of the array. For example, slice(-2) returns a copy of the last two elements. With splice(-1, 1), the last element is removed. An index beyond the array’s length is treated differently by the methods, so use valid, deliberate indexes when positions come from user input.
Frequently Asked Questions
Can I use split on a JavaScript array?
No. split() is a string method. For arrays, use slice() to copy a range, splice() to remove or replace elements, or filter() to group by a condition.
How do I split an array into two arrays?
Choose a boundary index and call slice(0, boundary) and slice(boundary). Both results are new arrays, and the source array remains unchanged.
Does splice change the original array?
Yes. splice() mutates the array on which it is called. It returns the elements it removed, which may be an empty array if it only inserts items or removes none.
How do I split an array into chunks?
Loop through the array in increments of the desired chunk size and use slice(start, start + size) for each chunk. The last chunk can contain fewer elements than the others.
What is the difference between split and splice?split() separates a string into an array using a separator. splice() changes an array by removing, inserting, or replacing elements. They operate on different kinds of values and solve different problems.
Related
- JavaScript split() Method: Turn a String Into an Array
- SQL Server STRING_AGG: Syntax, Examples, and Limits
- How to Split an Activity in P6: Step-by-Step Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Wedding Budget Spreadsheet Templates: How to Choose OneWedding budget spreadsheet templates are preformatted Excel or Google Sheets files for listing costs, setting spending limits, and…
- How to Import a CSV File From Linux to ExcelTo import a CSV file created on Linux, first copy it to a folder Windows can access, then…
- How to Clear Cache Data in OutlookTo clear cache data in Outlook, first identify which Outlook version you use: in classic Outlook for Windows,…
- Excel Keyboard Shortcut to Select a Row in Any WorksheetIn Excel for Microsoft 365 on Windows, press Shift+Space to select the entire worksheet row containing the active…
- Excel Print Area: Where to Find, Set, and Clear ItIn Excel for Microsoft 365 on Windows, find Print Area on the Page Layout tab: choose Page Layout…
- How to Freeze Panes in Excel: Keep Rows and ColumnsTo freeze panes in Excel for Microsoft 365 on Windows, select the cell immediately below the rows and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.