Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables:

var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]";
var json2 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]";

How can I create a variable containing only the IDs in an array?

var ids1 = json1.ids (resulting in 1,2)
var ids2 = json2.ids (resulting in 1,2,3)

Furthermore, how can I create another variable with only the IDs that are different between the two arrays?

var idsdiff = diff(ids1, ids2) (resulting in 3)

Answer №1

var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
    json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
    result1 = json1.map(function (a) { return a.id; }),
    result2 = json2.map(function (a) { return a.id; });

var differences = result2.filter(function (item) {
    return result1.indexOf(item) < 0;
});

console.log(result1);
console.log(result2);
console.log(differences);

Note that indexOf, filter, and map may not work in iE versions before iE9.

UPDATE: According to @alexandru-Ionutmihai's comment, filter will fail on arrays like [1,2,4] and [1,2,3]

This revised code seems more accurate:

var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
        json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
        result1 = json1.map(function (a) { return a.id; }),
        result2 = json2.map(function (a) { return a.id; });

//as per @alexandru-Ionutmihai this is inaccurate for [1,2,4] and [1,2,3]
/*var differences = result2.filter(function (item) {
    return result1.indexOf(item) < 0;
});*/

//here's a workaround
function findDifferences(a, b) {
  var i,
    la = a.length,
    lb = b.length,
    res = [];
  if (!la)
    return b;
  else if (!lb)
    return a;
  for (i = 0; i < la; i++) {
    if (b.indexOf(a[i]) === -1)
      res.push(a[i]);
  }
  for (i = 0; i < lb; i++) {
    if (a.indexOf(b[i]) === -1) res.push(b[i]);
  }
  return res;
}

var differences = findDifferences(result1, result2),
  testDiff = findDifferences([1, 2, 4], [1, 2, 3]);

console.log(result1);
console.log(result2);
console.log(differences);
console.log(testDiff);

findDifferences credit to @Nomaed's comment on this question's answer.

Answer №2

To find the difference between two sets of values, you can utilize a hash table to store the IDs and their occurrences. Then, filter out the IDs with a count that is not zero to get the unique values.

function getId(a) { return a.id; }

var obj1 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]');
var obj2 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]');
var ids1 = obj1.map(getId);
var ids2 = obj2.map(getId);
var hash = {};

ids1.forEach(function (a) {
    hash[a] = 1;
});
ids2.forEach(function (a) {
    hash[a] = (hash[a] || 0) - 1;
});

var difference = Object.keys(hash).filter(function (a) { return hash[a]; }).map(Number);
console.log(ids1);
console.log(ids2);
console.log(hash);
console.log(difference);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For a symmetrical difference, you can make use of lodash's _.xor method.

var ids1 = [1, 2],
    ids2 = [1, 2, 3];

console.log(_.xor(ids1, ids2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Answer №3

If you haven't already parsed the JSONs, an additional step is required:

json1 = JSON.parse(json1);

If they have been parsed, please implement this code snippet instead:

var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];

// Additional steps if needed
// json1 = JSON.parse(json1);
// json2 = JSON.parse(json2);

function returnID (item) {
    return item.id;
};

json1 = json1.map(returnID);
json2 = json2.map(returnID);

var diff = json2.filter(function (item) {
    return json1.indexOf(item) < 0;
});

console.log(diff);

Answer №4

To compare two sets of JSON data, you can utilize the map method along with the filter method.

var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
    return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
    return j2.indexOf(el)==-1;
}));
console.log(diff);

This code is designed to work effectively when the IDs present in both JSON arrays are different from each other.

var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 4, "name":"y"}, {"id": 5, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
    return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
    return j2.indexOf(el)==-1;
}));
console.log(diff);

Answer №5

For populating arrays with only the id attributes of each object, you can simply do...

var ids1 = json1.map(x => x.id)
var ids2 = json2.map(x => x.id)

If you are using ES6 or a version transpiler, you have the option to utilize the spread operator to find the variance between the two like so:

var diff = [...ids1.filter(x => !ids2.includes(x)), ...ids2.filter(x => !ids1.includes(x))]

var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];

var ids1 = json1.map(x => x.id);
var ids2 = json2.map(x => x.id);

var diff = [...ids1.filter(x => !ids2.includes(x)), ...ids2.filter(x => !ids1.includes(x))];
console.log(diff);

Answer №6

Below are two functions provided for you to achieve your desired results:

Function One (retrieveIds):

var data1 = [{"id": 1, "name":"apple"}, {"id": 2, "name":"banana"}];
var data2 = [{"id": 1, "name":"apple"}, {"id": 2, "name":"banana"}, {"id": 3, "name":"cherry"}];

function retrieveIds (data) {
    return data.map(function (object) {
        return object.id;
    });
}

console.log(retrieveIds(data1));
console.log(retrieveIds(data2));

Function Two (findDifference)

var data1 = [1, 2, 4, 6];
var data2 = [1, 2, 3];

function findDifference (arr1, arr2) {
    return arr1.concat(arr2).filter(function (num, index, array) {
        return array.indexOf(num) === array.lastIndexOf(num);
    });
}

console.log(findDifference(data1, data2));

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

The differential treatment of arrays' values in comparison to manually inputted values

Here is a function that I have: public function getReward($formattedArray, $key){ $id = $formattedArray[$key][0]; //dd($id); //Returns 1 $reward = Item::find($id); return $reward; } The problem arises when executing this part of the code ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Activate/Deactivate toggle using Vue.js

new Vue({ el: '#app', data: { terms: false, fullname: false, mobile: false, area: false, city: false, }, computed: { isDisabled: function(){ return !this.terms && !this.fullname && !this.mob ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Control the access to shared resources when dealing with asynchronous functions in JavaScript

Currently, I am developing a node.js server script that will utilize a shared text list for multiple clients to access asynchronously. Clients have the ability to read, add, or update items within this shared list. static getItems(){ if (list == undef ...

Combine a JSON object and a JSON array by matching the value of the JSON object to the key of the JSON array

I am looking to create a JSON array in node by combining two JSON objects and arrays. `var template = { "key1": "value1", "key3": "value3", "key4": "value3", "key6": "Dummy Value1" }; var data = [ { "value1": "1", "value2": "2", ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

How to iterate over the request body in Node.js using Express?

When I send a request with data in the form of an array of objects: [ {id: "1"}, {id: "2"}, {id: "3"} ] I am utilizing JSON.stringify() and my req.body ends up looking like this: { '{"id":"1"} ...

Challenges faced when retrieving data from a web API using JavaScript with REACT

Having trouble retrieving data from a Web API in React. The API URL is and I've stored it in a state called pokeData. When I do a console.log(pokeData), everything works fine. Likewise, there are no issues with console.log(pokeData.types). However, ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

programming for the final radio button text entry

I am struggling with a form that has 5 radio buttons, including an "other" option where users can manually enter text. The issue I'm facing is that the form only returns the manual entry text and not any of the preset radio values. I need it to work f ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

Issue with Jquery UI sortables not functioning properly

Struggling with getting a sortable list to work using jQuery UI. The ul element is receiving the class 'ui-sortable' but nothing seems to be happening. To demonstrate this issue, I created an example since the original javascript code is quite c ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Guide to importing the Slider Component in React using Material-UI

I am trying to incorporate the Slider Component from @material-ui/core into my React project. However, when I attempt to import the Slider using this code: import Slider from '@material-ui/lab/Slider';, it gives me an error stating Module not fou ...

What is the best way to compress JSON responses?

During a recent interview, I encountered a question that asked how to minify a JSON response. Here is the sample JSON response: { "name": "sample name", "product": "sample product", "address": "sample address" } I am unsure of how to minify this J ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Styling tables within HTML emails for Gmail and then utilizing PHPMailer to send the emails

I've been racking my brain over this for hours with no luck! Objective: Implementing inline styles for table, td, th, p elements in an HTML email intended for Gmail using PHPMailer. Challenge: Inline styles not being rendered HTML Snippet: <sec ...