How to insert an item into an array at a specific index (JavaScript)?

后端 未结 20 2141
灰色年华
灰色年华 2020-11-21 07:05

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implem

相关标签:
20条回答
  • 2020-11-21 07:58

    Other than splice, you can use this approach which will not mutate the original array, but will create a new array with the added item. You should usually avoid mutation whenever possible. I'm using ES6 spread operator here.

    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]

    This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well

    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]

    0 讨论(0)
  • 2020-11-21 07:58

    Here's a working function that I uses in one of my application.

    This checks if item exit

    let ifExist = (item, strings = [ '' ], position = 0) => {
         // output into an array with empty string. Important just in case their is no item. 
        let output = [ '' ];
        // check to see if the item that will be positioned exist.
        if (item) {
            // output should equal to array of strings. 
            output = strings;
           // use splice in order to break the array. 
           // use positition param to state where to put the item
           // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position. 
            output.splice(position, 0, item);
        }
        //empty string is so we do not concatenate with comma or anything else. 
        return output.join("");
    };
    

    And then I call it below.

    ifExist("friends", [ ' ( ', ' )' ], 1)}  // output: ( friends )
    ifExist("friends", [ ' - '], 1)}  // output:  - friends 
    ifExist("friends", [ ':'], 0)}  // output:   friends: 
    
    0 讨论(0)
  • 2020-11-21 07:59

    I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you, 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 ...)

    0 讨论(0)
  • 2020-11-21 08:03

    Here are two ways :

    const array = [ 'My', 'name', 'Hamza' ];
    
    array.splice(2, 0, 'is');
    
    console.log("Method 1 : ", array.join(" "));

    OR

    Array.prototype.insert = function ( index, item ) {
        this.splice( index, 0, item );
    };
    
    const array = [ 'My', 'name', 'Hamza' ];
    array.insert(2, 'is');
    
    console.log("Method 2 : ", array.join(" "));

    0 讨论(0)
  • 2020-11-21 08:05

    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);
    
    0 讨论(0)
  • 2020-11-21 08:06

    Append Single Element at a specific index

    //Append at specific position(here at index 1)
    arrName.splice(1, 0,'newName1');
    //1: index number, 0: number of element to remove, newName1: new element
    
    
    //Append at specific position (here at index 3)
    arrName[3] = 'newName1';
    

    Append Multiple Element at a specific index

    //Append from index number 1
    arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
    //1: index number from where append start, 
    //0: number of element to remove, 
    //newElemenet1,2,3: new elements
    
    0 讨论(0)
提交回复
热议问题