Find the matching objects in two arrays by comparing their unique ids

There are two arrays containing objects. One array includes objects with an id property that holds a list of ids, while the other array contains objects with a unique id property. The goal is to filter the ids in the second array based on the ids in the first list and retrieve the corresponding data.

const data1 = [{
  name: 'A',
  ids: [1, 2, 3]
}, {
  name: 'B',
  ids: [4, 5, 6]
}, {
  name: 'C',
  ids: [7, 8, 9]
}]

const data2 = [{
    id: 1,
    color: 'red'
  }, {
    id: 2,
    color: 'black'
  }, {
    id: 3,
    color: 'blue'
  }, {
    id: 4,
    color: 'yellow'
  }, {
    id: 5,
    color: 'green'
  }, {
    id: 6,
    color: 'pink'
  },
  {
    id: 7,
    color: 'orange'
  }, {
    id: 8,
    color: 'white'
  }, {
    id: 9,
    color: 'teal'
  }
]

const arrayToObject = (array) =>
  array.reduce((obj, item) => {
    obj[item.id] = item
    return obj
  }, {})

console.log(arrayToObject(data2))

const newData = data1.map(item => {
  return {
    name: item.name,
    data: item.ids.map(i => arrayToObject(data2)[i])
  }
})

console.log(newData)

Expected Output:

[
  {
    "name": "A",
    "data": [
      {
        "id": 1,
        "color": "red"
      },
      {
        "id": 2,
        "color": "black"
      },
      {
        "id": 3,
        "color": "blue"
      }
    ]
  },
  {
    "name": "B",
    "data": [
      {
        "id": 4,
        "color": "yellow"
      },
      {
        "id": 5,
        "color": "green"
      },
      {
        "id": 6,
        "color": "pink"
      }
    ]
  },
  {
    "name": "C",
    "data": [
      {
        "id": 7,
        "color": "orange"
      },
      {
        "id": 8,
        "color": "white"
      },
      {
        "id": 9,
        "color": "teal"
      }
    ]
  }
]

I've successfully obtained the desired output, but I believe there might be a more efficient and cleaner solution. Any recommendations would be appreciated.

P.S: I'm also open to leveraging lodash.

Answer №1

You've already mastered the traditional approach:

  1. Start by creating a dictionary or Map based on the id
  2. Use Array.map() to iterate over data1
  3. Retrieve the items from the dictionary based on the ids

To streamline the code, consider leveraging lodash:

  1. Utilize _.keyBy() to create a dictionary
  2. Access items from the dictionary by employing _.at()

const data1 = [{"name":"A","ids":[1,2,3]},{"name":"B","ids":[4,5,6]},{"name":"C","ids":[7,8,9]}]
const data2 = [{"id":1,"color":"red"},{"id":2,"color":"black"},{"id":3,"color":"blue"},{"id":4,"color":"yellow"},{"id":5,"color":"green"},{"id":6,"color":"pink"},{"id":7,"color":"orange"},{"id":8,"color":"white"},{"id":9,"color":"teal"}]

// create the dictionary
const dict = _.keyBy(data2, 'id')

// get the items from the dictionary
const newData = data1.map(({ ids, ...item }) => ({ ...item, data: _.at(dict, ids) }))

console.log(newData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

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

Best practices for efficiently extracting surface points from a Nx3 point cloud array using numpy

Imagine having a numpy array (with the shape of Nx3, where each row represents a point in 3D space as (x, y, z)) forming a point cloud. Now, I aim to create a heightmap from this point cloud by projecting it onto the xy plane. The goal is to identify the m ...

When XML is accessed through an iframe, it is interpreted as HTML

In my endeavor to display an xml file within an HTML page using an iframe and altering the content through jQuery by manipulating the source attribute, I encountered a curious issue. When I viewed the xml file directly in my browser (Firefox/Chrome/IE8), i ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Javascript Error: Fictitious Path Troubles

When attempting to retrieve the file path, it displays as follows: "C:\fakepath\amine.jpeg", causing an issue with uploading the file to the server. $('input[type=file]').change(function () { var filePath = $('#file-input&apo ...

One controller displays ng-repeats while the other does not

I have 2 controllers loading in different locations within my view. One controller works perfectly, but the other one does not show ng-repeats or appear in ng-inspector. I have confirmed that the http data is visible in the inspector. Both controllers are ...

Reset the select boxes when a button is clicked

I'm currently utilizing Devextreme within my Angular application, and I have three dx-selectbox elements in the component. I am attempting to clear all three dropdown selections when clicking a "clear" button. Unfortunately, I am unable to find a way ...

Is there a way to determine when a Telegram web app specifically designed for bots has been shut down?

I have created a Telegram bot that opens a web app, whether through an inline button, keyboard, or link. Once the user completes the tasks in the web app, they can close it using the "close" button instead of any button within the web app that I can track. ...

How to implement dynamic color for classes in a v-for loop using Vue.js?

Struggling with a seemingly simple issue that may be easy for VueJS pros. In my data, I have JSON objects with an attribute that can take values of 10, 20, 30, or 40. Depending on this value, I want to change the color of a v-btn. I've attempted mul ...

Struggling to modify a document in a MongoDB collection with an HTTP Put request?

I've recently started working with AngularJS and I encountered an issue while trying to update my MongoDB Database. I'm facing a problem when attempting to update an object within my collection. The code snippet below showcases my approach: //li ...

Encountering a 415 Error while making an ajax call using formData

I am attempting to make an ajax call with formData that includes a list of image files and some strings. However, the call is not successful and I am receiving error 415. Here is the code: var file = picChooser.files[0]; var jobExecutionImagesContext = n ...

Utilize Apollo to retrieve a variety of queries at once

Currently, I'm utilizing nextJS for my frontend development along with Apollo and GraphQL. For fetching queries, I am using the getStaticProps() function. To enhance modularity and maintainability, I have segmented my queries into multiple parts. The ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Mapbox is capable of managing several GEOJSON files by utilizing the loadURL function

I am in the process of creating a map that is designed to load multiple layers from various sources based on a configuration file called config.json. Each layer should trigger a popup when clicked, but oddly enough, I am only able to see the popup for the ...

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

Changing the link color within a repeater in ASP .NET when it is clicked

The given code snippet is being executed on an iPhone 4, causing some CSS elements like Hover to not function as expected. <asp:Repeater ID="rpt" runat="server"> <HeaderTemplate> <div class="table withshadow"> </Header ...

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

Eliminating unnecessary commas in a string array in Java

I am working with an array of strings and need to eliminate any additional commas from the elements. String[] myList= new String[]{"hello","Mr","How","are","You",}; What is the best way to remove these extra commas from the string array? ...

Is there a way for me to link my script for use in a Detail.cshtml file?

I have added the following script to my _Layout.cshtml shared master view: <script src="@Url.Script("~/Scripts/PromptToSave.js")" type="text/javascript"></script> Is there a way to include this script in a Details or index page that does not ...