How to write JavaScript unshift and shift array methods from scratch

·

1 min read

How to write JavaScript unshift and shift array methods from scratch

unshift

Add an element to the front of an array

Array.prototype._unshift = function(...values) {
  const newArray = [...values, ...this]
  this.length = 0
  this.push(...newArray)

  return this.length;
};

const fruits = ['apple', 'mango', 'banana']

fruits._unshift('orange', 'pineapple')

console.log(fruits)
// Output
// ['orange', 'pineapple', 'apple', 'mango', 'banana']
  • create a new array with values and array elements in it.

  • make the array length equal to 0 so, it makes the array empty.

  • now, push the newArray elements to the array.

  • return length of the array.

shift

Remove the element from the front of an array.

Array.prototype._shift = function() {
    if(this.length === 0) {
        return
    }

  const firstElement = this[0]

  for(let i = 0; i < this.length; i++) {
      this[i] = this[i+1]
  }

  this.length--

  return firstElement
}

const fruits = ['apple', 'mango', 'banana', 'orange']

console.log(fruits._shift())
// Output
// apple
  • if the array length is 0 return undefined.

  • store the first element

  • shift the array to the right by 1

  • decrease the array length

  • return first element