0

I have an array of objects which is similar to:

Questions-answers  [{"questions":"Q_18002_Error_message","answers":"Yes"},{"questions":"Q_18002_Error_message","answers":"No"},{"questions":"Q_18001","answers":"No"}]

I want to delete {"questions":"Q_18002_Error_message","answers":"Yes"} because I have a new updated answer to the question Q_18002, I am a newbie in Javascript and I am stuck on how to delete the duplicate elements but based on the questions only and delete the old ones and leave the new objects. I hope that I made it clear.

Paze
  • 183
  • 1
  • 1
  • 11
Hkni
  • 115
  • 1
  • 11

1 Answers1

0

You may build up the Map (with Array.prototype.reduce()) using questions as a key, overwriting previously seen values, then extract array of unique records with Map.prototype.values():

const src = [{"questions":"Q_18002_Error_message","answers":"Yes"},{"questions":"Q_18002_Error_message","answers":"No"},{"questions":"Q_18001","answers":"No"}],
 
      result = [...src
        .reduce((r,o) => (r.set(o.questions,o), r), new Map)
        .values()
      ]
      
console.log(result)
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • Can you please explain these lines for me if it is possible? what was the use of the points next to src ? – Hkni Aug 03 '20 at 09:28
  • 1
    @Houdakilani : `Map.prototype.values()` returns iterator object, so those 3 dots inside square brackets ([spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)) are used to actually iterate `Map` values and put those into array. If anything else confuses you, feel free to ask. – Yevhen Horbunkov Aug 03 '20 at 10:06