'how to filter array to only pick last changed value of same id of object in react

This is the function i run on OnChange in AvField

let selectedFieldArray = []

const templateValue = (e) => {
    const fieldObject = {
      "id": e.target.name,
      "value": e.target.value,
    }
    selectedFieldArray.push(fieldObject)
    const uniqueID = selectedFieldArray.filter((obj, id, array) => {
      return id === array.findIndex((t) => (
        t.id === obj.id
      )) 
    })
  }

but in uniqueID it only picks first object of array not the last updated object in array.



Solution 1:[1]

Instead of using arr.findIndex you can use arr.findLastIndex

let selectedFieldArray = [];
const templateValue = (e) => {
  const fieldObject = {
    "id": e.target.name,
    "value": e.target.value,
  }
  selectedFieldArray.push(fieldObject) const uniqueID = selectedFieldArray.filter((obj, id, array) => {
    return id === array.findLastIndex((t) => (t.id === obj.id))
  })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heet Vakharia