Home > Software engineering >  How to remove duplicate object from array in JavaScript
How to remove duplicate object from array in JavaScript

Time:10-21

I am working on an array, Actually, I have a dropdown list. I am pushing that object into an array but I am facing one issue actually when I select something it shows two elements at the same time like in dropdown let suppose if I have options ( option1, option2, option3). For example, I have selected option1 it pushed object value as option1 but when I select option2 it also pushed it into an array. I want unique values like if I select options2 it should be select recent value.

 generateExtraFieldData = (data, name, index, type, value, values) => {
const { projectFloorData, unitModifiedData } = this.state
let obj = projectFloorData[name]
obj['data'] = data
let tempArr = [...unitModifiedData]

tempArr.push(obj)

this.setState({ unitModifiedData: this.uniqueFiles(tempArr) })

// projectFloorData[name].data = data

}

 uniqueFiles = (data) => {
    let unique = _.uniqBy(data, 'index')
    console.log('@@ array', unique)
    return unique
  }

I have used lodash but it just return ist selected value, I need a recent value like if the user selected a second time

CodePudding user response:

Try using yourArray.length = 1;, this limit you array to an int limit. And if you select another option, just do yourArray.length = 0 to clear the array and then again yourArray.length = 1; to store the new option.

CodePudding user response:

why are you pushing your selected value into your array if you want to select a single value at a time try an object instead of an array and change the value/ reassign the value on selection.

  • Related