What is the best way to eliminate a duplicate key-value pair from a JSON array?

Consider the following JSON data:

[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

I'm looking to determine if the key "id" has duplicate values. If duplicates are found, I want to remove the earlier instances of the JSON with the same "id" in order to obtain a modified JSON Array with unique "id" values.

[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

Is there a JavaScript solution for achieving this?

Answer №1

If you want to iterate through an array from the end and only add unique elements based on a specific criteria, you can utilize the reduceRight method.

var data = [{"name": "John", "id": 1}, {"name": "Don", "id": 2}, {"name": "Tom", "id": 3}, {"name": "NewJohn", "id": 1}, {"name": "Tim", "id": 4}]

var result = [] 
data.reduceRight(function(r, e) {
  if(!r[e.id]) {
    result.unshift(e);
    r[e.id] = 1;
  }
  return r;
}, {})

console.log(result)

Answer №2

Try this code snippet for a solution to your issue:

var dataArray = [{"name": "John", "id": 1}, {"name": "Don", "id": 2}, {"name": "Tom", "id": 3}, {"name": "NewJohn", "id": 1}, {"name": "Tim", "id": 4}];
    var seenIds = {};

dataArray = dataArray.reverse().filter(function(currentItem) {
    if (currentItem.id in seenIds) {
        return false;
    } else {
        seenIds[currentItem.id] = true;
        return true;
    }
});

console.log(dataArray)

Answer №3

let newMap = createMap(data.map(item => [item.id, item]));

You have the option to convert it into a Map.. and then destructure it into an array:

newMap = [...newMap].map(element => element[1]);

http://jsbin.com/zuqabonebe/edit?console

Answer №4

Through the use of two nested for loops, I am able to remove the duplicate id property from a given set of data.

var data=[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}];

function deleteJsonProperty(dataJson){
for(var i=0;i<dataJson.length;i++){  
  for(var z=i+1;z<dataJson.length;z++){
  if(dataJson[i].id===dataJson[z].id){
    delete dataJson[i].id;
  }
  }
}
  return dataJson;
}
console.log(deleteJsonProperty(data));

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

Comparing DOM Creation in PHP and JavaScript

My website currently does not have any ajax requests, and here is a simplified version of my code: class all_posts { public function index($id){ $statement = $db->prepare("SELECT * FROM mytable WHERE id = :id"); $statement->exe ...

What is the method to clear the value of a specific key within an associative array in PHP without removing the key?

My array named $aFilter looks like this (Output of print_r($aFilter);): Currently, only one internal array element is displayed, but it can contain multiple elements. Let's consider the scenario with multiple internal array elements. Array( ...

Ways to safeguard function constructor arrays from unauthorized alterations using get methods in JavaScript

I am dealing with a coding challenge that involves managing state in JavaScript. Here is the code snippet I have been working on: function State(){ const SecretState = { name: 'bob' } this.getState = () => SecretState; this.setStat ...

Display modal popup only once the dropdown has been validated, with the validation focusing on criteria other than the dropdown itself

Looking for a way to validate dropdown values. Popup should only show if the dropdown values are selected; otherwise, the popup should remain hidden. Below is the code snippet: <div class="main-search-input-item location"> ...

Establishing a read stream from a folder and transferring the entire contents of the folder to a MongoDB Bucket

I encountered an issue while attempting to save an entire directory to a MongoDB Bucket. Although the process is successful when I zip the file, I specifically need the files to be uploaded in their unzipped format into the bucket. However, when I try to ...

The value of innerHTML is currently "undefined"

I am facing a new challenge while working with PHP. I need to edit the content of a div using the product ID fetched from the database. I am trying to accomplish this by iterating through two foreach loops to get the correct IDs separately. The goal is to ...

Limiting style changes to specific labels in Highcharts

Can someone assist me in bolding only the middle elements of a highcharts x axis? I have tried to apply a solution in the provided fiddle but it doesn't work as expected. Specifically, I am looking to bold the x-axis labels for June or July. http://j ...

The JavaScript code will automatically execute loops

Let me illustrate my point with two functions. Function 1 This function triggers a transition when you hover over the square. If you move your mouse off the element and then back on while the transition is still in progress, it will wait until the end of ...

Error in NodeJS Mongoose: Undefined value causing inability to call the 'toString' method

I am having an issue with displaying the name of a Team from my database on the web page. Here is the code snippet I am using: var Team = require('../schemas/Team').Model; app.get('/match', function(req, res) { var key = 1359407087 ...

Iterating through lines within a String Array

In my program memory, I have an array containing text const char* const paragraph[] PROGMEM = { "First Line", "Second Line" }; What is the method to read each string individually and output them one at a time? First Line Second Line ...

Displaying a List of Files Uploaded with Jquery File Upload in an ASP.NET MVC Application

I have successfully installed the NuGet Jquery File Upload Plugin. The uploader functions flawlessly, allowing me to easily drag and drop files for upload to my server. However, there are two issues that are hindering the completion of this project: Aft ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

Revamp the recursive associative array transformation

We start with an array that contains the following values: $a = array("a", "a.b", "a.b.c", "X", "X.Y", "X.Y.Z"); The objective here is to transform the initial array into the structure shown below: $a = array( "a" => array( "b" => ar ...

how to extract data from script tags (window.__INITIAL_STATE__) in HTML using Python

I'm having issues with parsing data using Python. The data includes a mix of byte type and string: "https:\u002F\u002Finvest.zum.com\u002Finternal\u002Findex\u002F1" The data I received is not being converted to ...

Ways to prevent a React component from re-rendering when a sibling component re-renders

Recently, I've delved into the world of React and Redux but hit a snag. I have a button that triggers an API call to fetch information about cars. The process goes like this: Upon button click, it dispatches the function getCars(), which then trigger ...

Simultaneous extraction of Json data from a database

Imagine this scenario: I am reading data from a datareader in a separate task, which returns a single column result set in the form of a JSON string. As I read each JSON string, I add it to a BlockingCollection that wraps a ConcurrentQueue. Simultaneously, ...

The act of scrolling through list elements does not initiate upon the first click

I'm trying to create a script that allows users to scroll through list elements by clicking on "previous" and "next" links. However, I'm running into an issue where when the user clicks on the "next" button for the first time, they have to click ...

The URL provided by window.location is not accurate

I'm facing an issue with the code window.history.pushState("", "title", myCtxURLVersion); which is supposed to change the current URL of the page. However, when I implement this code, the URL displayed is incorrect. For example, even though the brows ...

Formik's handleSubmit function seems to be being overlooked and not executed as

I've encountered an issue while trying to validate a form before submission using formik and yup validation. The form is divided into two parts, where the first part needs to be validated before moving on to the second part. I set a state handleShow(t ...

What specific flag should be included in Chrome settings to prevent displaying c:/fakepath?

Is there a way to disable this security feature? I'm seeking a solution in Chrome to obtain the full file path of an uploaded or viewed file, similar to how it can be done in Internet Explorer. Despite my efforts with flags like --allow-file-access-f ...