In Javascript, you can compare an array with a nested array and then store the values in a new array

Two arrays are at hand

const arrayOne = [
 {id: '110'},
 {id: '202'},
 {id: '259'}
];

const arrayTwo = [
 {data: [{value: 'Alpha', id: '001'}]},
 {data: [{value: 'Bravo', id: '202'}]},
 {data: [{value: 'Charlie', id: '752'}]},
 {data: [{value: 'Delta', id: '202'}, {value: 'Sierra', id: '110'}]},
 {data: [{value: 'Echo', id: '937'}]}
];

The task is to generate a new array by comparing arrayOne[idx].id with arrayTwo[idx].data[idx2].id

If there is a match, the new array should contain either the value or the entire matching object.

Using this example, the expected result would be

newArray = ['Bravo', 'Delta', 'Sierra']

My attempts so far include:

let result = arrayOne.map(el => {
  let found = arrayTwo.find(f => f.data.at(0)?.id == el.id)?.data.at(0)?.value;
  return { id: el.id, value: found ?? null};
});

const result = arrayTwo
  .map(obj => obj.data[0])
  .map(obj => (arrayOne.find(v => v.id === obj.id) && obj.value))

arrayOne.map(item => ({
   ...item,
   result: arrayTwo.filter(itemTwo => item.data.map(x => x.id).includes(itemTwo.id))
}));

Answer №1

Ensure you check all indices, not just the first one:

let found = arrayTwo.find(f => f.data.at(0)?.id == el.id)?.data.at(0)?.value;

If the initial index doesn't match, other indices may still contain the desired values and should not be overlooked.

Simplicity is key here. Create a Set of IDs to search for, then iterate over each .data array element, adding matching objects to the output array.

const arrayOne=[{id:"110"},{id:"202"},{id:"259"}],arrayTwo=[{data:[{value:"Alpha",id:"001"}]},{data:[{value:"Bravo",id:"202"}]},{data:[{value:"Charlie",id:"752"}]},{data:[{value:"Delta","id":"202"},{value:"Sierra","id":"110"}]},{data:[{value:"Echo",id:"937"}]}];

const idsToFind = new Set(arrayOne.map(({ id }) => id));
const output = [];
for (const { data } of arrayTwo) {
  for (const obj of data) {
    if (idsToFind.has(obj.id)) output.push(obj.value);
  }
}
console.log(output);

If you prefer a more concise solution:

const arrayOne=[{id:"110"},{id:"202"},{id:"259"}],arrayTwo=[{data:[{value:"Alpha",id:"001"}]},{data:[{value:"Bravo",id:"202"}]},{data:[{value:"Charlie",id:"752"}]},{data:[{value:"Delta","id":"202"},{value:"Sierra","id":"110"}]},{data:[{value:"Echo","id":"937"}]}];

const idsToFind = new Set(arrayOne.map(({ id }) => id));
const output = arrayTwo
  .flatMap(({ data }) => data.filter(
    obj => idsToFind.has(obj.id)
  ))
  .map(obj => obj.value);
console.log(output);

Answer №2

Instead of iterating through the objects inside the array within the data property, we can iterate through the array itself to create an array of arrays. By utilizing flat(), we can consolidate these arrays into a single array containing {value, id} objects. Subsequently, we can search for the id by iterating over this consolidated array.

It is important to note that this approach may introduce duplicate values. To prevent duplicates, one solution is to utilize a Set and spread its unique values into a new array.

An alternative method to avoid duplicates involves implementing a condition in the forEach loop that uses the find() method to check if the value already exists in the output array.

const arrayOne = [
 {id: '110'},
 {id: '202'},
 {id: '259'}
];

const arrayTwo = [
 {data: [{value: 'Alpha',id: '001'}]},
 {data: [{value: 'Bravo',id: '202'}]}, 
 {data: [{value: 'Charlie',id: '777'}, {value: 'Sierra', id: '259'}]},
 {data: [{value: 'Delta',id: '202'}, {value: 'Sierra', id: '259'}]}
];

const output = [];

arrayTwo
  .map(obj => obj.data)
  .flat()
  .forEach(obj => (arrayOne.find(v => v.id === obj.id) && output.push(obj.value)))
  
console.log('Output:', output)

const uniqueOutput = [...new Set(output)]
console.log('Unique Output:', uniqueOutput)

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

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

Using JSON to dynamically generate pages in Gatsby programatically

Currently, I am utilizing Gatsby to dynamically generate pages, and I am looking to do so at two distinct paths: covers/{json.name}.js and styles/{json.name}.js. While I have successfully set this up using the gatsby-node.js file, I would like to transit ...

Using AJAX within the $.when function to extract the first character from the returned string

Currently, I am utilizing an AJAX call by using $.when to wait for the completion of that specific ajax request and then continue with processing the subsequent ajax request inside. The code block below demonstrates where the $.when method is being invoke ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code: var ...

Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved fr ...

Arrangement of div elements tailored to fit the size of the viewport

I am working on creating a grid of divs that will cover the entire viewport. To start, I want to have a grid that is 7 divs wide and 10 divs high. Below is the code snippet I've written so far to set the size of the div elements: function adjustHeig ...

Steps to extract an array from a data frame

Is there a way to extract an array from a column in a data frame based on a certain condition? For instance: data = data.frame(pn=c('a','b','c','d','e','f'), price=c(1,2,3,4,5,6)) If we have a l ...

Remove the initial 15,000 lines from a text file using Node.js

Looking for a way to delete the first 15,000 lines of a large text log file (roughly 20MB) using Node.js. Any suggestions on how to accomplish this task? ...

The error "Call to a member function exports() on array" occurs when attempting to use the

As I attempt to send an array of values to the jobExport() collection, I encounter an error stating Call to a member function jobsExport() on array. I comprehend the necessity for the collection to be populated with modal collection value. However, my goal ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

What is the best way to retrieve data from this array?

Some of the code I have extracted from serialized data appears to not be in an array format. When attempting to use a foreach loop, it results in an error. array ( 'last_submit' => '1', 'feeds_changed' => '1', ...

Updating Ajax data leads to improved sorting capabilities

When making an AJAX call on my Wordpress site, everything works perfectly except for the sorting of the data in the SUCCESS function. If I use print_r ($service), I can see that the correct custom order is being validated However, after sending it using: ...

What is the best way to interact with a checkbox that has a label using Selenium in Node.js?

My HTML document contains multiple checkbox classes with different texts for each checkbox name. Here is a snippet of the HTML code: <div class="col-md-12 syllabus-div-1"> <h4 class="vertical-spacing">Coaching<i class="fa fa-graduation- ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there. I am curious to know how I can transform the code below from an OnClick event to a timed event. For instance, I would like to refres ...