I have a state array that looks similar to this
this.state = {
var: "",
arr1: [],
other: ["item1", "item2", "item3"]
}
In my render()
I list out the contents of the "other" array, and next to it, a user can put any number, which would be their ranking (doesn't matter if repeated) of the items in the "other array as shown below
<Row className="App">
<ul>
{this.state.other.map((item, index) =>
<li key={index}>{item}<Input className="rankCols" type="number" id="ranking" onChange={this.handleChange.bind(this, item)} /></li>
)}
</ul>
</Row>
Then in a handleChange
function, I store the user ranking in an array of objects along with the pName
handleChange = (item, event) => {
const value = event.target.value
this.setState(prev => {
const idx = prev.arr1.findIndex(obj => obj.pName === item)
if (idx > -1) {
return {
arr1: [...prev.arr1.slice(0, idx), {
pName: item,
priority: value
}, ...prev.arr1.slice(0, idx + 1)]
}
} else {
return {
arr1: prev.arr1.concat([{
pName: item,
priority: value
}])
}
}
});
}
Now the problem is that, instead of the arr1
looking like
arr1: [{
pName: "item1",
priority: "3"
},
{
pName: "item2",
priority: "1"
},
{
pName: "item3",
priority: "2"
}
]
It repeats the some of the values so it looks more like
arr1: [{
pName: "item1",
priority: "3"
},
{
pName: "item2",
priority: "1"
},
{
pName: "item3",
priority: "2"
},
{
pName: "item1",
priority: "3"
},
{
pName: "item2",
priority: "1"
},
{
pName: "item3",
priority: "2"
}
]
So it gives me problems in the backend, because each item cannot exist more than once. How could I prevent them from repeating?