2

I would like to implement a sort of insertion-sort or order a Javascript array. Basically I have to reorder an array while inserting a new item in an existing index. Example:

Index: 1 - Value: 400
Index: 3 - Value: 660
Index: 5 - Value: 593

I would insert a new value, 800 at index 3, so the already existing item should shift forward:

Index: 1 - Value: 400
Index: 3 - Value: 800
Index: 4 - Value: 660
Index: 6 - Value: 593

How I can do this in js?

Chilledrat
  • 2,593
  • 3
  • 28
  • 38
Ras
  • 628
  • 1
  • 11
  • 29
  • possible duplicate of http://stackoverflow.com/questions/586182/javascript-insert-item-into-array-at-a-specific-index – forsvunnet Nov 21 '13 at 17:33

1 Answers1

0

With javascript you don't have much flexibility with keys in arrays. You might be looking for the array.splice function which allows you to insert items at the specified index.

An example:

var arr = [];
arr[1] = 400;
arr[3] = 660;
arr[5] = 594;

arr.splice(3, 0, 800);
// arr is now = [undefined × 1, 400, undefined × 1, 800, 660, undefined × 1, 594]

As you can see the array now contains undefined values for in the unspecified indexes (0,2 and 5).

If you seek greater control over the indexes you will have to retort to using objects.

With objects you can either reverse loop through the array and increasing the index for one item at the time (the previous overwriting the next) or create a new object based on the old.

Here is an example using the latter method:

var obj = {1:400, 3:660, 5:593};
var push_index = function(index, value) {
  var push_i = index;
  var new_obj = {};
  for (var i in obj) {
    if (i == push_i) {
      push_i++;
      new_obj[push_i] = obj[i];
    } else {
      new_obj[i] = obj[i];
    }
  }
  new_obj[index] = value;
  return new_obj;
};
obj = push_index(3, 800);

Please note that this only works if the object is already sorted.

forsvunnet
  • 1,238
  • 10
  • 17