Combining two different arrays in JavaSscript to create a single array

I have two arrays, one representing parents and the other representing children in a relational manner. I need to combine these into a single array.

Parent array: const cat = ['a','b','c']; Child array:

const sub =[{name:'cloth',cat:['a','b']},{name:'feshion',cat:['b','a']}]

After combining the two arrays using map and filter methods, the expected output should be:

const parent =[{name:'a',sub:['cloth','feshion']},{name:'b',sub:['cloth','feshion']},{name:'c',sub:[]}]

I've tried using map and filter but it's not working as expected. Can someone please help me with this and provide any ideas?

Answer №1

const output = pets.map(type => ({type, toys: toys.filter(t => t.pets.includes(type)).map(t => t.name)}));

Results in:

[
   { "type": "dog", "toys": ["ball", "bone"] },
   { "type": "cat", "toys": ["mouse", "feather"] },
   { "type": "bird", "toys": [] }
]

This is a more detailed version of the same line for better understanding:

const output = pets.map(petType => {
   const petToys = toys
      .filter(t => t.pets.includes(petType))
      .map(t => t.name);

   return {type: petType, toys: petToys};
});

Execute the code:

const pets = ['dog','cat','bird'];
const toys =[{name:'ball',pets:['dog']},{name:'mouse',pets:['cat']},{name:'bone',pets:['dog']},{name:'feather',pets:['cat']}];
const output = pets.map(type => ({type, toys: toys.filter(t => t.pets.includes(type)).map(t => t.name)}));
console.log(output);

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 you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

How to assign a click event to dynamically generated HTML elements using jQuery

My goal is to attach an onclick event to a dynamically inserted element using jQuery However, I am facing an issue where the function does not execute. I would appreciate it if someone could help me determine why this example is not functioning correctly ...

What is the process of exporting a module assigned to a variable in JavaScript?

My approach to making the require visible in <app></app> is as follows: index.html: <script> var electron = require('electron') </script> <app></app> <script src="bundle.js"></script> App.vue: ...

If every object within the array contains a value in the specified property, then return true

In my current project, I am working with an array of objects that looks something like this: $scope.objectArray = [ {Title: 'object1', Description: 'lorem', Value: 57}, {Title: 'object2', Description: 'ipsum', V ...

The presence of Bootstrap remains hidden unless space is designated for it

Question about Bootstrap 5.1.3: Is there a way to hide elements on a page using the bootstrap class ".invisible" without allocating space for them? Currently, when the elements are set to visible using the class ".visible", they occupy space on the page ...

Query an array of objects for partial matches that are not case-sensitive, and then organize the results in alphabetical order

I am seeking assistance or guidance on which topics to explore for answers. As a newcomer to React, I have a code that successfully filters a list within the items object. However, I would like to switch to using a prepared JSON file instead. When I attem ...

Exploring the process of transforming a dynamic PDF into a static PDF using PHP or NodeJS

Issue I am looking for a PHP/NodeJS API that can convert editable PDF files to non-editable PDFs online. Our client application requires the user to download PDF files that cannot be modified using software like Foxit Reader or Adobe. We are currently us ...

Tips for handling the rejection of a promise within a callback function in Node.js

How can we effectively incorporate a catch statement within a rejectionCallback function of a promise? Is it feasible or advisable to structure the code in this manner? Would the Promise object need to be passed into the rejection function in such a scena ...

Can a 2D array be constructed with the row index arranged in descending order?

In my Python project, I am developing a game grid using a 2D array. The challenge I am facing is that when the grid is printed, I want the first column of each row to display a row label in reverse order (1 at the bottom and 5 at the top). Is there a way t ...

Tips for obtaining the identifier of a div element while employing the bind() function in jQuery

Imagine having the following div. <div id="456" class="xyz">Lorem Ipsum</div> If I want to execute a function when this specific div is hovered over, I can achieve it like this: $(".xyz").bind({ mouseenter : AnotherFunction(id) }); Prio ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

The width of an HTML input and button elements do not match

Currently, I am facing an unusual issue where my input and button tags seem to have the same width assigned to them (width: 341.5px; calculated from $(window).width() / 4) in the code, but visually they appear to be of different widths. Here is a visual re ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...

How to handle a POST request with an empty body in Node.js express routing, utilizing body-parser

I'm facing an issue where my submission form's post requests are returning an empty body, regardless of the body parser settings I apply. All my dependencies in package.json are up to date, and a previous application I created (using the deprecat ...

Building React applications with server-side rendering using custom HTML structures

I recently started using Suspense in my React app and decided to implement SSR. However, as I was going through the documentation at https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream, I couldn't find a clear explanation on how to u ...

Top method for changing an array in javascript

I'm in the process of building a react application, and I've received the following array from an API call. var arrayLike ={ "2020-W1": [ { "type": "TAX_REFUND_IN_INT", &q ...