Determine the distinct values from two arrays and store them in a separate array using JavaScript

In my scenario, I have two arrays in JavaScript as shown below:

First array:

count_array[0].left= 0;
count_array[0].width= 33;
count_array[0].id= 1;
count_array[1].left= "";
count_array[1].width= "";
count_array[1].id= 2;
count_array[2].left= "";
count_array[2].width= "";
count_array[2].id= 3;

Second array:

temp_array[0].left= "";
temp_array[0].width= "";
temp_array[0].id= 4;
temp_array[1].left= "";
temp_array[1].width= "";
temp_array[1].id= 5;
temp_array[2].left= 0;
temp_array[2].width= 33;
temp_array[2].id= 1;

The objective here is to extract an array with unique id values from the first two arrays, resulting in the following:

Third array:

temp_array_cnt[0].left= 0;
temp_array_cnt[0].width= 33;
temp_array_cnt[0].id= 1;

I attempted to achieve this using the code snippet below, however it did not work as expected:

function intersection(x,y){
  x.sort();y.sort();
 var i=j=0;ret=[];
 while(i<x.length && j<y.length){
  if(x[i]<y[j])i++;
  else if(y[j]<x[i])j++;
  else {
    ret.push(x[i]);
    i++,j++;
   }
  }
 return ret;

}

Your assistance in resolving this issue would be greatly appreciated.

Currently, I am utilizing the function provided below:

   function intersection(x,y){
ret=[];
//x.sort();y.sort();
for(var i=0;i<x.length;i++)
{
 for(var j=0;j<y.length;i++)
 {
    //console.log(x[i].eventid);
    var chk_left=x[i];
    if(chk_left.id == chk_left.id)
    {
        ret.push(chk_left);
    }
 }
}
   return ret;
   }

Unfortunately, this implementation is throwing an error stating "id is null or not an object".

Answer №1

let sum = 0;

for(let i = 0; i < countArray.length; i++) {
    for(let j = 0; j < tempArray.length; i++) {
        if(countArray[i].id == tempArray[j].id) {
            tempArrayCount[sum].left = countArray[i].left;
            tempArrayCount[sum].width = countArray[i].width;
            tempArrayCount[sum].id = countArray[i].id;
            sum++;
        }
    }
}

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

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

The method used in Redux does not function properly with my sessionStorage

I am currently in the process of learning about Redux. One of my goals is to implement a favorites feature using Redux. To achieve this, I have created actions such as addFavoriteSPORTSs, SPORTSReducer reducers, and have dispatched them in tab-demo.js whil ...

Exploring the wonders of LoopBack querying

Discovering loopback has been an enlightening experience for me. However, as I delve deeper into its functionalities, I've stumbled upon something unexpected. I noticed that when executing queries, such as using the updateAll method, if a parameter i ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

instructions for selecting div id within the same "table td" element using jQuery

Here is the code snippet that I am working with: <td> <div id="div<%# Eval("Id") %>" class="Display"><%# Eval("Display") %></div> <div class="Actions"> </div> <div class="Comment"> <span>Comm ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

Adjust the width of a div based on its height dimension

I have a div called #slideshow that contains images with a 2:1 aspect ratio. To set the height of the image using jQuery, I use the following function: Keep in mind that the Slideshow Div is always 100% wide in relation to the browser window. If the use ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

grunt-webpack claims to have completed without any errors, yet it has failed to bundle any files

Over the past week, I've been attempting to get grunt, babel, and webpack to work together smoothly. Despite trying various solutions that I found during my research, nothing seems to be working as intended. Below is the relevant portion of my gruntfi ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

Sending an array using the POST method with Ajax

It's puzzling, this seemingly straightforward issue has me stumped. I can't seem to figure out why it's happening, and I haven't come across anyone else experiencing the same problem. Here's the dilemma: I'm sending a POST re ...

Encountering "Maximum call stack" errors while executing a recursive function

I have developed a height map editor that functions as a grid of numbers, allowing users to adjust any location by +/- 1. The editor enforces a rule where there can only be a difference of 1 between any of the adjacent 8 tiles. To achieve this functionali ...

Encountering a hitch while attempting to integrate a framework in Angular JS 1

Having experience with Angular JS 1 in my projects, I have always found it to work well. However, I recently encountered a project that uses Python and Django, with some pages incorporating Angular. The specific page I needed to work on did not have any An ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

Using QuerySelector with Angular Directive will throw an error as it is not a recognized

When creating a directive that integrates a jQuery carousel, I want to hide it at the beginning until it is fully ready. Here's the directive code snippet: return { restrict: 'E', replace: true, scope: true, templateUrl: ...

What causes the choppy and inconsistent performance of requestAnimationFrame on Ubuntu's Chrome browser?

I'm at a loss here, unsure of what might be causing this issue. After developing a game engine with webgl, I conducted testing primarily on Firefox where everything ran smoothly without any lag or stuttering, even during more intensive tasks like ble ...

Creating an array of input data for component, implementing data formatting in TypeScript for Angular or React applications

Here is an example of the input for the component. When this input is passed to the component, the output displays correctly. const data = [ ['Rank', 'Player', 'Player', 'Player'], ['1& ...

Excluding null values when using Mongoose populate query: A simple guide

I'm currently working on an app where I've defined 2 models. const UserSchema = new Schema({ _id: Schema.Types.ObjectId, account:{ type: String, unique: true }, email: String, first_name: String, last_name ...

Tips for efficiently reading a large volume of documents (1M+) from a collection in Cloud Firestore?

Encountering an error of 9 FAILED_PRECONDITION: The requested snapshot version is too old. const ref = db.collection('Collection'); const snapshot = await ref.get(); snapshot.forEach((doc,index) => { ...utilize data }) Want to retrieve all ...