I’m looking for a simple way to JavaScript insert into array at a specific position—something like:
arr.insert(index, item)
I’d prefer a jQuery-style approach if available, but any clean JavaScript solution would work. What’s the best way to insert an element at a given index in an array?
After a few years of wrangling data-heavy apps, one method that’s never failed me is splice()
.*
It’s probably the most direct and widely known approach for a javascript insert into array task.
function insertIntoArray(arr, index, item) {
arr.splice(index, 0, item);
}
let arr = ['apple', 'banana', 'cherry'];
insertIntoArray(arr, 1, 'orange');
console.log(arr); // ['apple', 'orange', 'banana', 'cherry']
This works perfectly when you’re okay with modifying the original array. The key here is 0
—it means we’re not removing anything, just dropping in the new item.
Yeah, totally agree with @charity-majors —splice()
is reliable. But in cases where immutability matters (think React state updates), I usually lean into a more functional approach. With a decade of JS under my belt, I’ve come to appreciate this pattern using slice()
and the spread operator."*
function insertIntoArray(arr, index, item) {
return [...arr.slice(0, index), item, ...arr.slice(index)];
}
let arr = ['apple', 'banana', 'cherry'];
const newArr = insertIntoArray(arr, 1, 'orange');
console.log(newArr); // ['apple', 'orange', 'banana', 'cherry']
This way, you get a brand new array, and the original remains untouched. It’s one of the cleanest ways to handle a javascript insert into array without side effects.
Both great answers! I’ve found that if you’re working in a team or building utilities you’ll reuse, extending Array.prototype
can really clean up your code. After years of working in large-scale JS codebases, a little syntactic sugar goes a long way.
Array.prototype.insert = function(index, item) {
this.splice(index, 0, item);
};
let arr = ['apple', 'banana', 'cherry'];
arr.insert(1, 'orange');
console.log(arr); // ['apple', 'orange', 'banana', 'cherry']
This approach makes your code more expressive—closer to natural language. While it’s still using splice()
under the hood, attaching the method to the prototype gives a slick and reusable javascript insert into array utility that feels like jQuery but is pure vanilla JS.