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

后端 未结 20 2143
灰色年华
灰色年华 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 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);
    

提交回复
热议问题