0

I have this kind of array of object:

[
  {variable: "contactPhone", title: "Phone", type: "text"},
  {variable: "contactName", title: "Name", type: "text"}
]

Each time on click I'm dynamically adding new objects in array. It is actually a clone one of the objects depending on which one user clicked. So I need to sort them like this, contactPhone to be always on top, contactName on the bottom:

[
  {variable: "contactPhone", title: "Phone", type: "text"},
  {variable: "contactPhone", title: "Phone", type: "text"},
  {variable: "contactPhone", title: "Phone", type: "text"},
  {variable: "contactName", title: "Name", type: "text"},
  {variable: "contactName", title: "Name", type: "text"},
]

here what I'm trying to do, but it doesnt work. Any ideas ?

addNewInput(i) {
    const { data, index } = this.state
    let cloned = { ...data[index].variables[i] }
    const newData = this.state.data
    newData[index].variables.push(cloned)
    data[index].variables.sort((a, b) => (a.variable === b.variable ? 1 : -1))
    this.setState({
      data: newData,
    })
  }
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67

0 Answers0