What is the best way to identify and delete duplicate rows in a JSON array?

Suppose we have two variables, x and y. The task at hand is to compare these variables using JavaScript code in order to generate the output by eliminating any duplicate data.

Duplicate data here refers to instances where both x and y contain values: 202, 203, 204, 205.

var x = [{'pID': 200},{'pID': 201},{'pID': 202},{'pID': 203},{'pID': 204},{'pID': 205}];
var y = [{'fID': 202},{'fID': 203},{'fID': 204},{'fID': 205}];
output = [{'ID': 200}, {'ID': 201}];

How can this be achieved? The two variables share some common data points but with different key names. Please advise if there are any errors in my naming conventions.

The JSON array x functions as the primary data source, meaning it contains more data than the JSON array y.

Thank you.

Answer №1

If you're looking for a simple solution, using filter and map can do the trick. First, apply the filter and then map the result type. Since all items in b are present in a, this approach should work smoothly.

a.filter(aIt => !b.find(bIt => bIt.fID === aIt.pID)).map(res => ({'ID': res.pID}))

Check out this working example:

var a = [{'pID': 200},{'pID': 201},{'pID': 202},{'pID': 203},{'pID': 204},{'pID': 205}];
var b = [{'fID': 202},{'fID': 203},{'fID': 204},{'fID': 205}];

var res = a.filter(aIt => !b.find(bIt => bIt.fID === aIt.pID)).map(res => ({'ID': res.pID}));

console.log(res);

Alternatively, you can use reduce to skip the additional mapping step:

a.reduce((res, aIt) => (!b.find(bIt => bIt.fID === aIt.pID) && !res.push({ID: aIt.pID}) || res), []);

Here's another working example with reduce:

var a = [{'pID': 200},{'pID': 201},{'pID': 202},{'pID': 203},{'pID': 204},{'pID': 205}];
var b = [{'fID': 202},{'fID': 203},{'fID': 204},{'fID': 205}];

var res = a.reduce((res, aIt) => (!b.find(bIt => bIt.fID === aIt.pID) && !res.push({ID: aIt.pID}) || res), []);

console.log(res)

Tip: You can also consider using the some method to filter effectively, as it returns true or false more directly compared to find which returns an object or undefined.

Answer №2

To find unique values, you can combine two arrays and calculate the occurrences of each value using the array#reduce method.

var array1 = [{'id': 100}, {'id': 101}, {'id': 102}, {'id': 103},{'id': 104}, {'id': 105}];    
var array2 = [{'id': 102}, {'id': 103}, {'id': 104}, {'id': 105}];

var mergedArray = array1.concat(array2).reduce((result, value) => {
  var val = Object.values(value)[0];
  result[val] = (result[val] || 0) + 1;
  return result;
},{});

var uniqueValues = Object.keys(mergedArray).reduce((resultArray, key) => {
  if(mergedArray[key] == 1)
    resultArray.push({ID : key});
  return resultArray;
},[]);
console.log(uniqueValues);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To simplify the process, start by extracting the values from the object and then utilize the filter method to eliminate duplicates.

var getValues = ( array ) => array.reduce( (a,b) => a.concat( Object.values( b ) ), [] );
var getCommonValues = ( arr1, arr2 ) => arr1.filter( item => arr2.indexOf( item ) == -1 );

var arrayA = getValues(a); // retrieve values from object A
var arrayB = getValues(b);

var result = arrayA.length > arrayB.length ? 
         getCommonValues(arrayA, arrayB) : getCommonValues(arrayB, arrayA) ; // use the larger array as the first parameter

Example

var a = [{
  'pID': 200
}, {
  'pID': 201
}, {
  'pID': 202
}, {
  'pID': 203
}, {
  'pID': 204
}, {
  'pID': 205
}];
var b = [{
  'fID': 202
}, {
  'fID': 203
}, {
  'fID': 204
}, {
  'fID': 205
}];
var getValues = (arr) => arr.reduce((a, b) => a.concat(Object.values(b)), []);
var getIntersection = (a, b) => a.filter(item => b.indexOf(item) == -1);

var arrayA = getValues(a); //get the values
var arrayB = getValues(b);
var output = arrayA.length > arrayB.length ?
  getIntersection(arrayA, arrayB) : getIntersection(arrayB, arrayA);

console.log(output);

Answer №4

To eliminate repeated values that are unwanted, you can utilize the Array Filter method in JavaScript. The approach involves fetching all values from variable b and then removing objects from variable a that share the same values.

// sample data
var a = [{'pID': 200},{'pID': 201},{'pID': 202},{'pID': 203},{'pID': 204},{'pID': 205}];
var b = [{'fID': 202},{'fID': 203},{'fID': 204},{'fID': 205}];

// extract values from variable b
var bValues = b.map((element) => (element.fID));

// filter out elements in variable a based on values in bValues
var result = a.filter((element) => {
    return (bValues.indexOf(element.pID) === -1);
});
console.log(result);

Answer №5

To only check the keys ending with ID, you can utilize a Set. Remove the values from the second array and create a new array with those remaining.

var firstArray = [{ pID: 200 }, { pID: 201 }, { pID: 202 }, { pID: 203 }, { pID: 204 }, { pID: 205 }],
    secondArray = [{ fID: 202 }, { fID: 203 }, { fID: 204 }, { fID: 205 }],
    getValue = obj => obj[Object.keys(obj).find(key => key.endsWith('ID'))],
    set = new Set(firstArray.map(obj => getValue(obj))),
    result;

secondArray.forEach(obj => set.delete(getValue(obj)));

result = Array.from(set, ID => ({ ID }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

Having trouble with Vuetify's 'text-wrap' class not functioning properly for wrapping text to the next line? Find out

I'm encountering an issue where words get cut off on my cards and are moved to a new line. Here is an image showing the problem: https://i.sstatic.net/9mWbx.png I attempted to resolve this issue by using the class="text-wrap", but it did no ...

Unleashing the hidden power of a website's jQuery function - the ultimate guide!

I am looking to modify the delayedAutoNext function found on the homepage of pitchfork.com which rotates the pitchfork.tv images. My goal is to adjust the setTimeout value to a new number. Is there a way to accomplish this using a bookmarklet or userscrip ...

"Create a stunning backdrop with animated wave effects using JavaScript

I am currently using three.js to create a waves canvas animation, but I am unsure how to eliminate the background-color (only the background-color) of the canvas. if (WEBGL.isWebGLAvailable() === false) { document.body.appendChild(WEBGL.getWebGLErrorMes ...

In Java, what is the process of converting a string in the format {a=2 ,b=5} to a JSON object in the format {"a":2 , "b":5}?

I have received the outcome as {a=2 ,b=5} following the evaluation of a SpEL expression. I would like to convert it into json format. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated! ...

No closing bracket was found as the NodeJS & Jade string reached its conclusion

Embarking on my journey into the world of node.js (following the steps in the rolling with mongo tutorial), I have created a jade file which looks like this: extends layout block content h1= title form(method="post") div div span Tit ...

Troubleshooting issue in Django: 'QueryDict' object does not contain 'read' attribute when working with ajax json object

Currently, I am struggling with parsing a JSON object in my Django view that was sent over by the client using Ajax through the POST method. JavaScript: $.post('/update_vendor_merchandise_types/', JSON.stringify(json_obj)) View: def update_ve ...

The versions of Node and Nodejs differ from each other

As I dive into learning Node.js, I attempted to install the software. However, my efforts have brought about conflicting results. When I run node -v, it shows v4.4.4, but when I try nodejs -v, it displays v0.10.45 The commands which node and which nodejs ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

Guide to fetching input control value dynamically inserted via javascript

In my PHP view, I have implemented a button that adds textboxes to the page within a form. However, when trying to retrieve the value of these dynamically added textboxes in my PHP controller, the value is not present. Is there a solution for obtaining t ...

What is the correct way to utilize the wordcount function with the meteorhacks:npm package?

I recently added the meteorhacks/npm package to my Meteor app so that I could utilize the Wordcount package within it. Unfortunately, I'm encountering difficulties with my method implementation. On the client-side: getWordcount = function getWord ...

Meteor: accounts-ui Package - Simplifying User Authentication in Your

I am interested in implementing the accounts-ui package to handle account management within my application. However, the current sign-in form appears as a drop-down menu. Is there a way to encapsulate it within a button so that clicking on the button wil ...

The focusable attribute in SVG is malfunctioning

I've utilized the focusable attribute to ensure SVG elements receive focus within an HTML document. My goal is to navigate through SVG elements in the SVG tag using the TAB key, as indicated in this resource (http://www.w3.org/TR/SVGTiny12/interact.h ...

Ensure that the form is validated when the radio buttons belonging to an unfamiliar group are

Looking to implement form validation that only triggers when all group radio buttons are checked. The challenge is making this dynamic as the number of radio button groups may vary. Is there a way to determine the number of groups in a form? This functio ...

Is there a way to automatically include virtual fields when querying nested documents in Mongoose?

I have created the following schema for my project: // data.js ... const dataSchema = new Schema( { title: { type: String } }, { toJSON: { virtuals: true }, toObject: { virtual: true } } ); // example vir ...

Serializing Json Objects in .Net MVC with HttpClient

Whenever I attempt to serialize my Model into Json for a POST request, I consistently receive a 400 Bad Request error due to an unserialized object. public class AppVersionModel { public Project project { get; set; } public String active { get; s ...

Using Object Value as Variable instead of String in JavaScript/React

When working with React & JavaScript, I am storing an input name as a string in an object: window.ObjectOne = { ObjectOneKey: "MyInputName", } The input name can be an object path like "Object.FirstName" or a variable name "MyVariableName" What I am at ...

The final value is always returned by jQuery's each method

Is there a way to prevent the .each() function from selecting the last value every time it runs? var items = ["item1", "item2", "item3"]; $("#list li").each(function() { var addedClass; if ($(this).hasClass("one")) { addedClass = "red"; } else ...

Search input in Handsontable header periodically clears when scrolling

Encountering a problem with preserving search terms in text input fields within HoT headers. After entering a search term and scrolling down, the term often gets cleared. This issue seems to be linked to the freeze behavior of HoT headers during scrolling. ...