Javascript Array insert(index, item)

Description

Javascript Array insert(index, item)




Array.prototype.insert = function (index, item) {
    this.splice(index, 0, item);//from  w  w  w  . j a  v a2 s .  c  om
};

Javascript Array insert(index, item)

Array.prototype.insert = function(index, item) {
  var args = this.slice.call(arguments),
      index = args.shift();//from   w  w w . j a  v a2s. c o m

  args = [index,0].concat(args);
  this.splice.apply(this, args);

  return this;
}

var result = [1,2,3,4,7,8,9,10].insert(4,5,6);
console.log(result);


var insertArrayItem = function(array) {
  array.splice(4,0,5,6);
  return array;
}

var result = insertArrayItem([1,2,3,4,7,8,9,10]);
console.log(result);

Javascript Array insert(index, item)

Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item);//from ww  w.  j a  v  a2 s.  co m
};

function insertionSort (array) {
  var sorted = [];
  function backItUp(obj) {
    if(!sorted.length) return sorted.push(obj);
    for(var j=sorted.length-1; j>=0; j--) {
      if(obj.value >= sorted[j].value) {
        return sorted.insert(j+1, obj);
      }
      if(!j) sorted.unshift(obj);
    }
  }

  for(var i=0; i<array.length; i++) backItUp(array[i]);
  return sorted;
}

Javascript Array insert(index, item)

Array.prototype.insert = function(index, item) {
  this.splice(index, 0, item);/* ww  w . j  av a 2 s. c  o  m*/
  return this;
}



PreviousNext

Related