Вопрос: Как вставить элемент в массив по определенному индексу?


Я ищу метод вставки массива Javascript в стиле:

arr.insert(index, item)

Предпочтительно в jQuery, но любая реализация Javascript будет делать на этом этапе.


2026


источник


Ответы:


Вы хотите, чтобы spliceфункции собственного объекта массива.

arr.splice(index, 0, item);вставить itemв arrпо указанному индексу (удаление 0пункты сначала, то есть это просто вставка).

В этом примере мы создадим массив и добавим в него элемент в индекс 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());


3357



Вы можете реализовать Array.insertметодом:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Затем вы можете использовать его так:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

203



Пользовательский массив insertметоды

1. С несколькими аргументами и поддержкой цепочки

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    this.splice.apply(this, [index, 0].concat(
        Array.prototype.slice.call(arguments, 1)));
    return this;
};

Он может вставлять несколько элементов (как родных spliceделает) и поддерживает цепочку:

["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]

2. Слиянием массивов и объединением цепочек

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    index = Math.min(index, this.length);
    arguments.length > 1
        && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
        && this.insert.apply(this, arguments);
    return this;
};

Он может объединять массивы из аргументов с данным массивом, а также поддерживает цепочку:

["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"

DEMO: http://jsfiddle.net/UPphH/


63



Помимо сращивания, вы можете использовать этот подход, который не будет мутировать исходный массив, но создаст новый массив с добавленным элементом. Обычно вам следует избегать мутации. Я использую оператор распространения ES6 здесь.

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, newItem) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted item
  newItem,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10)

console.log(result)
// [1, 10, 2, 3, 4, 5]

Это можно использовать, чтобы добавить несколько элементов, немного изменив функцию, чтобы использовать оператор останова для новых элементов, и распространить это на возвращаемый результат

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, ...newItems) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted items
  ...newItems,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10, 20)

console.log(result)
// [1, 10, 20, 2, 3, 4, 5]


50



If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

Also here are some functions to illustrate both examples:

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

Finally here is a jsFiddle so you can see it for youself: http://jsfiddle.net/luisperezphd/Wc8aS/

And this is how you use the functions:

// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

33



For proper functional programming and chaining purposes an invention of Array.prototype.insert() is essential. Actually splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array. So here it goes

Array.prototype.insert = function(i,...rest){
  this.splice(i,0,...rest)
  return this
}

var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");

Well ok the above with the Array.prototype.splice() one mutates the original array and some might complain like "you shouldn't modify what doesn't belong to you" and that might turn out to be right as well. So for the public welfare i would like to give another Array.prototype.insert() which doesn't mutate the original array. Here it goes;

Array.prototype.insert = function(i,...rest){
  return this.slice(0,i).concat(rest,this.slice(i));
}

var a = [3,4,8,9],
    b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));


13



I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method in built-in Array which does the job, it's called splice...

Let's see what's splice()...

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

OK, imagine we have this array below:

const arr = [1, 2, 3, 4, 5];

We can remove 3 like this:

arr.splice(arr.indexOf(3), 1);

It will return 3, but if we check the arr now, we have:

[1, 2, 4, 5]

So far, so good, but how we can add a new element to array using splice? Let's put back 3 in the arr...

arr.splice(2, 0, 3);

Let's see what we have done...

We use splice again, but this time for the second argument, we pass 0, means we want to delete no item, but at the same time, we add third argument which is 3 that will be added at second index...

You should be aware, that we can delete and add at the same time, for example now we can do:

arr.splice(2, 2, 3);

Which will delete 2 items at index 2, then add 3 at index 2 and result will be:

[1, 2, 3, 5];

This is showing how each item in splice work:

array.splice(start, deleteCount, item1, item2, item3 ...)


6



Even though this has been answered already, I'm adding this note for an alternative approach.

I wanted to place a known number of items into an array, into specific positions, as they come off of an "associative array" (i.e. an object) which by definition is not guaranteed to be in a sorted order. I wanted the resulting array to be an array of objects, but the objects to be in a specific order in the array since an array guarantees their order. So I did this.

First the source object, a JSONB string retrieved from PostgreSQL. I wanted to have it sorted by the "order" property in each child object.

var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';

var jsonb_obj = JSON.parse(jsonb_str);

Since the number of nodes in the object is known, I first create an array with the specified length:

var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);

And then iterate the object, placing the newly created temporary objects into the desired locations in the array without really any "sorting" taking place.

for (var key of Object.keys(jsonb_obj)) {
  var tobj = {};
  tobj[key] = jsonb_obj[key].abbr;

  var position = jsonb_obj[key].order - 1;
  sorted_array[position] = tobj;
}

console.dir(sorted_array);

5



Another possible solution, with usage of Array#reduce.

var arr = ["apple", "orange", "raspberry"],
    arr2 = [1, 2, 4];

function insert(arr, item, index) {
    arr = arr.reduce(function(s, a, i) {
      i == index ? s.push(item, a) : s.push(a);
      return s;
    }, []);   
    console.log(arr);
}

insert(arr, "banana", 1);
insert(arr2, 3, 2);


4



I tried this and it is working fine!

var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);

Index is the position where you want to insert or delete the element. 0 i.e. the second parameters defines the number of element from the index to be removed item are the new entries which you want to make in array. It can be one or more than one.

initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");

1