Move an element to the beginning of the array in JavaScript

10 May

Move an element to the beginning of the array in JavaScript

Example Data

var options = [
  {
    "key": "Key1",
    "label": "Array-forEach",
    "content": {
      "type": "div",
      "props": {
        "children": "Standard shipping - 0 days"
      },
    }
  },
  {
    "key": "Key2",,
    "label": "Array-map",
    "content": {
      "type": "div",
      "props": {
        "children": "Standard shipping - 0 days"
      },
    }
  },
  {
    "key": "Key3",
    "label": "Array-reduce",
    "content": {
      "type": "div",
      "props": {
        "children": "Standard shipping - 0 days"
      },
    }
  }
]

Actual Code as function

// move selected options to top of the options Array
function moveSelectedElementToFrontOfArray(key, array) {
const arrayLength = array.length
for (let i=0; i < arrayLength; i++) {
if (array[i].key === key) {
const requiredItem = array.splice(i,1)
array.unshift(requiredItem[0])
break
}
}
return array
}

Calling the method

moveSelectedElementToFrontOfArray('Key3', options)

Bydr.code.skm

I am backend developer with passion in Web Application development using latest technologies like Laravel, PHP7, React, ECMAScript 6 and WordPress. I prefer spending time analyzing big data with Apache Spark. Apart from that, I do photography.