Eliminate repeated elements within an array of objects using JavaScript

My array contains objects that look like this:

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

I need to remove

{"questions":"Q_18002_Error_message","answers":"Yes"}
because I have an updated answer for question Q_18002. As a Javascript beginner, I am struggling with how to delete duplicate elements based on the questions only, keeping only the new objects. I hope that explanation is clear.

Answer №1

To create a unique array of records based on the `questions` key, you can utilize the Map (along with Array.prototype.reduce()) in JavaScript by setting `questions` as a key and then extracting the values using Map.prototype.values():

const source = [{"questions":"Q_18002_Error_message","answers":"Yes"},{"questions":"Q_18002_Error_message","answers":"No"},{"questions":"Q_18001","answers":"No"}],
 
      result = [...source
        .reduce((accumulator, current) => (accumulator.set(current.questions, current), accumulator), new Map)
        .values()
      ]
      
console.log(result)
.as-console-wrapper{min-height:100%;}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Designing a structure with a stationary header, immobile sidebar navigation, and unchanging content using flexbox styling

In the development of a web application, I am utilizing FlexBox for layout design. It is important to note that I am opting for pure flexbox CSS rather than incorporating Bootstrap. Desired Layout Structure: Row1: Consists of a fixed header 64px in heigh ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...

Having difficulty toggling checkboxes within a grid using the select all feature

In order to toggle checkboxes for a specific column within a grid, I encountered an issue within the JS "onUPCSelectAll" function with the eval statement displaying the following error message: JS runtime error: Object doesn't support property or meth ...

Merge two flat arrays together based on their index positions to create an associative array with predefined keys

These are my two arrays: Array ( [0] => https://google.com/ [1] => https://bing.com/ ) Array ( [0] => Google [1] => Bing ) Here is the desired JSON output: [ { "url": "https://google.com/", ...

Can you explain the distinction between these two concepts in JavaScript?

I've come across an issue while assigning PHP values to JavaScript. var a = <?php echo 39; ?> JavaScript is throwing an error that says "Uncaught SyntaxError: Unexpected token ILLEGAL". However, when I assign PHP values in a slightly different ...

Steps for correctly adding MomentJS in a Typescript project to fix the error: "The type 'typeof moment' does not have compatible call signatures."

I encountered an error when importing MomentJS that states: ERROR in [...] Cannot invoke an expression whose type lacks a call signature. Type 'typeof moment' has no compatible call signatures. Does anyone have suggestions on how to fix this is ...

Issues with Raphael function in a loop with Javascript

Still getting the hang of Javascript, so please be patient... I've set up two fiddles for comparison. The only variation between them is that one has a text object as a title while the other doesn't. Surprisingly, this tiny detail completely alt ...

Attaching and detaching children to and from parents using A-Frame

I'm currently working on developing an application similar to Google Street View that is able to capture and display images in a 360 Equirectangular format using Aframe. https://i.sstatic.net/hDSCv.gif One idea I have been considering involves makin ...

Ajax request received no data from API

I have been facing an issue with my code where I am posting an email on an API URL using an HTML form and PHP code with an Ajax call. However, the response I am getting is empty. I need to display this response on the same page below the form. I am sharing ...

Module 'path-to-regexp' not found

Currently, I am facing an issue while attempting to incorporate the library path-to-regexp into my TypeScript project. Despite using npm install path-to-regexp --save, with and without the --save flag, the import is still not functioning as expected. Upon ...

Using Webpack 4 to import SCSS files with aliases

Currently, I am running a node script that is using webpack to bundle multiple folders for various installations on our server. MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { ...

Can CSS be used for creating unique color combinations?

I am facing a challenge where I have two div elements with different transparent, colored backgrounds that overlap each other. My goal is to find a way to customize the color in the area where these elements overlap. For instance, if I blend red and blue ...

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Can Google Charts be integrated with $refs in VueJS?

I'm currently working on implementing a timeline chart with Google Charts. The chart is displayed within its own component, which I later invoke from a higher-level parent component. However, I've run into an issue where the drawChart function re ...

Adjust the height of the container div for the carousel according to the length of the text displayed

My image carousel features description content positioned on the right for wide-screen windows. However, I want the description to shift below the images when the browser window reaches a certain breakpoint. The challenge I am facing is that the height of ...

The resolvers contain the Query.Mutation but it is not specified in the schema

const { ApolloServer, gql } = require('apollo-server-express'); const express = require('express'); const port = process.env.PORT || 4000; const notes = [ { id: '1', content: 'This is a note', author: 'Adam ...

Issue with Nav Bar Toggle not changing text to white color

Query I'm baffled as to why the text in the navigation bar (when opened with the Burger Menu) refuses to turn white. I've exhausted all efforts to change the color to white. Please assist me in pinpointing why the text remains unaffected when t ...

Differences between jQuery form.id and form.id.value

Currently, I am working on a dokuwiki plugin and have stumbled upon an interesting issue regarding how javascript stores element ids. I am a bit confused about what is happening... Here is a snippet of code from the dokuwiki linkwiz.js file that checks if ...