← Назад к вопросам
Как вставить элемент в середину массива?
1.0 Junior🔥 71 комментариев
#JavaScript Core
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI2 апр. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Как вставить элемент в середину массива?
Вставка элемента в конкретную позицию массива — часто встречающаяся задача. Есть несколько способов в зависимости от того, нужно ли изменять исходный массив или создавать новый.
Способ 1: splice (изменяет исходный массив)
splice — это метод, который изменяет массив в месте (мутирует), удаляя и добавляя элементы.
const array = ["a", "b", "d", "e"];
// Вставить "c" в позицию 2 (перед "d")
// array.splice(startIndex, deleteCount, ...items)
array.splice(2, 0, "c");
console.log(array); // ["a", "b", "c", "d", "e"]
Параметры splice:
startIndex— позиция, где начать операциюdeleteCount— сколько элементов удалить (0 = не удалять)...items— элементы для вставки
Практические примеры
const nums = [1, 2, 5, 6];
// Вставить 3 и 4 в позицию 2
nums.splice(2, 0, 3, 4);
console.log(nums); // [1, 2, 3, 4, 5, 6]
// Вставить И удалить одновременно
const items = ["apple", "banana", "mango"];
items.splice(1, 1, "orange", "grape"); // Заменить banana
console.log(items); // ["apple", "orange", "grape", "mango"]
Способ 2: Spread оператор (создаёт новый массив)
Если нужен новый массив (не мутировать исходный), используй spread оператор.
const array = ["a", "b", "d", "e"];
const index = 2;
const newElement = "c";
// Создать новый массив с элементом в нужной позиции
const newArray = [
...array.slice(0, index), // ["a", "b"]
newElement, // "c"
...array.slice(index) // ["d", "e"]
];
console.log(newArray); // ["a", "b", "c", "d", "e"]
console.log(array); // ["a", "b", "d", "e"] — не изменился
Вставка нескольких элементов
const array = [1, 2, 5, 6];
const index = 2;
const newElements = [3, 4];
const newArray = [
...array.slice(0, index),
...newElements,
...array.slice(index)
];
console.log(newArray); // [1, 2, 3, 4, 5, 6]
Способ 3: concat (всегда создаёт новый массив)
const array = ["a", "b", "d", "e"];
const index = 2;
const newArray = array
.slice(0, index)
.concat(["c"])
.concat(array.slice(index));
console.log(newArray); // ["a", "b", "c", "d", "e"]
Способ 4: Функция для многократного использования
Вставка в место мутации (мутирует исходный массив)
function insertAt(array, index, ...items) {
array.splice(index, 0, ...items);
return array;
}
const arr = [1, 2, 5];
insertAt(arr, 2, 3, 4);
console.log(arr); // [1, 2, 3, 4, 5]
Вставка без мутации (создаёт новый массив)
function insertAtImmutable(array, index, ...items) {
return [
...array.slice(0, index),
...items,
...array.slice(index)
];
}
const arr = [1, 2, 5];
const newArr = insertAtImmutable(arr, 2, 3, 4);
console.log(newArr); // [1, 2, 3, 4, 5]
console.log(arr); // [1, 2, 5] — не изменился
Случаи использования
1. React: добавление элемента в состояние (ИММУТАБЕЛЬНО)
import { useState } from "react";
function TodoList() {
const [todos, setTodos] = useState(["Task 1", "Task 3"]);
const insertTodo = (index, newTodo) => {
// Создаём новый массив (не мутируем состояние)
setTodos([
...todos.slice(0, index),
newTodo,
...todos.slice(index)
]);
};
return (
<div>
{todos.map((todo, i) => <div key={i}>{todo}</div>)}
<button onClick={() => insertTodo(1, "Task 2")}>
Insert Task 2
</button>
</div>
);
}
2. Вставка в конкретную позицию пользователя
const insertBefore = (array, item, beforeItem) => {
const index = array.indexOf(beforeItem);
if (index === -1) return array; // Элемент не найден
return [
...array.slice(0, index),
item,
...array.slice(index)
];
};
const fruits = ["apple", "cherry"];
const newFruits = insertBefore(fruits, "banana", "cherry");
console.log(newFruits); // ["apple", "banana", "cherry"]
3. Вставка по условию
const insertIfNotExists = (array, item, index) => {
if (array.includes(item)) {
return array; // Уже есть
}
return [
...array.slice(0, index),
item,
...array.slice(index)
];
};
const items = [1, 2, 4];
console.log(insertIfNotExists(items, 3, 2)); // [1, 2, 3, 4]
console.log(insertIfNotExists(items, 1, 2)); // [1, 2, 4] — не добавилась
Сравнение подходов
const originalArray = ["a", "b", "d"];
const element = "c";
const position = 2;
// 1. splice — БЫСТРО, но мутирует
const arr1 = ["a", "b", "d"];
arr1.splice(position, 0, element);
// arr1: ["a", "b", "c", "d"]
// 2. spread — МЕДЛЕННЕЕ, но не мутирует
const arr2 = [
...originalArray.slice(0, position),
element,
...originalArray.slice(position)
];
// arr2: ["a", "b", "c", "d"]
// originalArray: ["a", "b", "d"] — не изменился
// 3. concat — МЕДЛЕННЕЕ, но не мутирует
const arr3 = originalArray
.slice(0, position)
.concat(element)
.concat(originalArray.slice(position));
// arr3: ["a", "b", "c", "d"]
Вставка в конец и начало (проще!)
const array = [2, 3, 4];
// Добавить в КОНЕЦ
array.push(5); // [2, 3, 4, 5] — мутирует
const arr1 = [...array, 5]; // новый массив
// Добавить в НАЧАЛО
array.unshift(1); // [1, 2, 3, 4] — мутирует
const arr2 = [1, ...array]; // новый массив
Производительность
const largeArray = Array.from({ length: 100000 }, (_, i) => i);
const position = 50000;
// БЫСТРО: O(n) где n = количество элементов после позиции
console.time("splice");
largeArray.splice(position, 0, "new");
console.timeEnd("splice"); // ~0.1ms
// МЕДЛЕННЕЕ: O(n) для всего массива (создаётся новый)
console.time("spread");
const newArray = [
...largeArray.slice(0, position),
"new",
...largeArray.slice(position)
];
console.timeEnd("spread"); // ~1-2ms
Выводы по производительности:
spliceбыстрее для больших массивов (мутирует)- Spread медленнее (создаёт копии)
- Для маленьких массивов разница незаметна
- В React/Redux ВСЕГДА используй иммутабельные методы
Резюме
| Способ | Мутирует? | Скорость | Использование |
|---|---|---|---|
| splice | Да | Быстро | Обычный JS, если можно мутировать |
| spread | Нет | Медленнее | React, Redux, иммутабельные структуры |
| concat | Нет | Медленнее | Редко, старый подход |
| slice + concat | Нет | Медленнее | Функциональное программирование |
Правило для React:
// ❌ Неправильно — мутирует состояние
setArray(array => {
array.splice(index, 0, item);
return array; // Может не триггерить перерендер
});
// ✅ Правильно — иммутабельно
setArray(array => [
...array.slice(0, index),
item,
...array.slice(index)
]);