What is the best way to compare two arrays of data and make changes?

I am working with two arrays, array A and array B

Here is how they look:

A:

[11, 14]

B:

[
  { title: 'title 1', data: [ { node_id: 11, selected: false }, { node_id: 14, selected: false } ]},
  { title: 'title 2', data: [ { node_id: 70, selected: false } ]}
]

This is the code I have written:

B.map((value) => {
  A.map((selectedDeviceId) => {
    value.data.map((valueData) => {
      selectedDeviceId === valueData.node_id
        ? (valueData.selected = true)
        : (valueData.selected = false);
    });
  });
});

However, when I check the B array, the output is:

[
  { title: 'title 1', data: [ { node_id: 11, selected: false }, { node_id: 14, selected: true } ]},
  { title: 'title 2', data: [ { node_id: 70, selected: false } ]}
]

I expected it to be:

[ { node_id: 11, selected: true }, { node_id: 14, selected: true } ]

Can you spot what's wrong in my code?

Answer №1

One way to achieve the desired result is by utilizing the Array.prototype.flatMap() function along with the Array.prototype.filter() method. By iterating through the array using flatMap and then applying the filter method alongside Array.prototype.some(), you can effectively filter out the node_ids.

const number = [11, 14];
const data = [
  {
    title: 'title 1',
    data: [
      { node_id: 11, selected: false },
      { node_id: 14, selected: false },
    ],
  },
  { title: 'title 2', data: [{ node_id: 70, selected: false }] },
];

const ret = data.flatMap((x) =>
  x.data.filter((y) => number.some((z) => z === y.node_id))
);
console.log(ret);

Answer №2

An efficient method of achieving the task.

const A = [11, 14];

const B = [{
    title: 'title 1',
    data: [{
      node_id: 11,
      selected: false
    }, {
      node_id: 14,
      selected: false
    }]
  },
  {
    title: 'title 2',
    data: [{
      node_id: 70,
      selected: false
    }]
  }
]
const updatedList = B.map((_b) => {
  return { ..._b,
    data: _b.data.map(_d => {
      return { ..._d,
        selected: A.includes(_d.node_id)
      }
    })
  }
})
console.log(updatedList)

Answer №3

const integers = [11, 14];
const objects = [
  { title: 'title 1', data: [ { node_id: 11, selected: false }, { node_id: 14, selected: false } ]},
  { title: 'title 2', data: [ { node_id: 70, selected: false } ]}
];

objects.forEach(obj => {
  integers.forEach(id => {
    const foundObject = obj.data.find(item => item.node_id === id);
    if (foundObject) {
      foundObject['selected'] = true;
    }
  });
});

console.log(objects);

Answer №4

After reviewing @mr hr's solution, it seems that the ternary operation in your code could use some adjustments. Consider revising it as follows:

B.map((value) => {
    A.map((selectedDeviceId) => {
        value.data.map((valueData) => {
          if(selectedDeviceId === valueData.node_id){
            valueData.selected = true;
          }
        });
    });
});

Answer №5

The mistake lies in the misuse of the map() function, rather than properly utilizing the results. The correct syntax should be:

.map(value => {return something;})
or .map(value => something)

Situations where map() should not be used

Since map creates a new array, it is considered an anti-pattern to use it when the returned array is not being utilized; instead, consider using forEach or for-of.

Source

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

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

How to implement file uploading with Node.js and Angular using the formidable module

I am having trouble uploading files with angular and nodejs using formidable. I can't seem to post anything to the server, despite trying the following code: server var form = new formidable.IncomingForm(); form.uploadDir = path.join(__dirn ...

Utilizing Vue.js: Dynamically linking v-model to route parameters depending on the current state

I'm currently in the process of developing an application that will serve as the backbone for a restaurant chain's website. The main functionality involves allowing users to modify page content and images. Given the complexity of the site with it ...

Playing Tic Tac Toe - How to prevent displaying results when an invalid move is made

I'm currently facing an issue with determining valid input for playing the game again. It seems to display the game results right after showing an invalid entry, prompting the user to enter "y" or "n" once more. I've attached a picture to illustr ...

Exploring the depths of Vue.js: Maximizing potential with nested

In my Grid component, I retrieve JSON data from a server and render it. The data mainly consists of strings and integers, but sometimes includes HTML elements like <strong>myvalue</stong>. In order to properly display the data, I use triple bra ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

"Utilize the most recent version of Uploadify to easily upload your

I am having trouble uploading a video using the latest version of uploadify. Here is my code: HTML: <form enctype="multipart/form-data" class="form-part" action="form.php" method="post"> <input class="uplodify" id="file_upload" type="file"/ ...

How can I effectively handle a JSON string list when receiving data from an AJAX call?

I am currently facing an issue with my ajax call that returns a serialized list of strings. Although I can retrieve the data, when trying to alert each item in the list, I only get single characters instead of the full string. For example, if the list cont ...

Combining arrays in Numpy with identical rows but varying columns

I have an array that contains the same rows but different columns than other arrays. I checked the shape of the array and confirmed that they have the same rows. print ("Type x_test : actual",type(x_dump),x_dump.shape, type(actual), actual.shape, pred.sha ...

"Encountering a 404 error in a JQuery Ajax POST request when trying to send

Recently, I have been working with Adobe InDesign extensions and one of the tasks involves uploading an XML file to a server using a jQuery AJAX POST call. To achieve this, I need to read the XML file from the file system, store it in a variable, and then ...

Is the Facebook AJAX Permissions Dialog displayed outside of a Pop-Up?

I have conducted extensive research but have failed to find a clear answer to my query. Although there is plentiful information on Facebook API AJAX/PHP communication, I am unable to locate an example where the Permission Dialog for an app (showPermissionD ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

Animation triggered when removing items from a filtered list using ng-repeat

I have a unique challenge where I need to display two different sections of an array in a single list by applying a filter within the ng-repeat. Instead of having two separate lists, I am filtering the array directly within the ng-repeat statement. While ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

Ways to update the state of an array without clearing the existing array items

I am attempting to add fetched array items to an existing state that already contains items (with plans to include pagination). However, when I try using code similar to setMovies((prevMovies) => [...prevMovies, ...arr1]), I encounter a Typescript erro ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

Guide on building a Dynamic factory in AngularJS

For my project, I need to implement a dynamic factory in AngularJS with a unique name. Here is an example of what I am trying to achieve: function createDynamicFactory(modId) { return myModule.factory(modId + '-existingService', function ...

Ember JS: Master of Controlling

I am working with the following controllers: clusters_controller.js.coffee Portal.DashboardClustersController = Ember.ArrayController.extend dashboard_controller.js.coffee Portal.DashboardController = Ember.ArrayController.extend In my template, I am ...

Is it possible for a beginner like me in Node.js to incorporate external npm packages into Express.js and React.js?

Recently, I embarked on a journey to learn Node.js for backend development. In the past month or so, I have familiarized myself with various concepts such as npm, Express.js, Mongoose, and MongoDB for database management. During my npm exploration, I dis ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts (https://www.highcharts.com/) only displays information for one of the points. Is there a way to make ...