Locate all elements in an array that contain a particular value for a specific key using Javascript

In my JavaScript data, I have two arrays:

ARRAY ONE:
[ TextRow { v_id: 3000 },
  TextRow { v_id: 3001 },
  TextRow { v_id: 3002 } ]

ARRAY TWO:
[ TextRow {
      s_id: 'S001',
      v_id: 3000,
      type: 'control' },
  TextRow {
      s_id: 'S002',
      v_id: 3001,
      type: 'mut' },
  TextRow {
      s_id: 'S003',
      v_id: 3001,
      type: 'mut' },
  TextRow {
      s_id: 'S005',
      v_id: 3001,
      type: 'control' },
  TextRow {
      s_id: 'S008',
      v_id: 3002,
      type: 'mut' } ]

I am looking for a way to match elements in Array One with related elements in Array Two. Specifically, I want to create new arrays in which each element from Array One corresponds to all elements from Array Two that share the same v_id value. For instance, if v_id = 3001 in Array One, I aim to collect all matching elements from Array Two where v_id equals 3001 into a separate array. However, I need help determining the most efficient approach for this task and whether there are built-in JavaScript functions that can streamline the process. Given the substantial size of my Array Two, consisting of over 1000 elements, I seek a solution that avoids simply iterating through elements using nested loops. Any suggestions or insights on optimizing this operation would be greatly appreciated.

Answer №1

To find the matching elements, you can utilize a combination of .forEach (or .map) on ARRAY_ONE and then a .filter on ARRAY_TWO.

A getMatches function has been included to enhance the clarity of the operation.

const ARRAY_ONE =
[  { id: 1000 },
   { id: 1001 },
   { id: 1002 } ];

const ARRAY_TWO =
[ {
      identifier: 'ID001',
      id: 1000,
      type: 'option' },
   {
      identifier: 'ID002',
      id: 1001,
      type: 'choice' },
   {
      identifier: 'ID003',
      id: 1001,
      type: 'choice' },
   {
      identifier: 'ID005',
      id: 1001,
      type: 'option' },
   {
      identifier: 'ID008',
      id: 1002,
      type: 'combination' } ];
      
function getMatches(id, array) {
    return array.filter(element => element.id === id);
}

const result = ARRAY_ONE.map(item => { 
    return { array_one_identifier: item.id, matches_found: getMatches(item.id, ARRAY_TWO) };
});

console.log("Final Output:", result);

Answer №2

To iterate through the initial array, utilize the .forEach( ) function.

Next, apply the .filter( ) method to the second array within the forEach loop as a callback function.

Your code may look something like this:

firstArray.forEach(item1 => secondArray.filter(item2 => item1.id == item2.id ) )

Answer №3

If you are looking to filter without grouping:

const firstArray =
[  { v_id: 3000 },
   { v_id: 3001 },
   { v_id: 3002 }
];

const secondArray =
[  {
      s_id: 'S001', v_id: 3000, type: 'control' },
   {
      s_id: 'S002', v_id: 3001, type: 'mut' },
   {
      s_id: 'S003', v_id: 3001, type: 'mut' },
   {
      s_id: 'S005', v_id: 3001, type: 'control' },
   {
      s_id: 'S008', v_id: 3002, type: 'mut' }
];    

const result = secondArray.filter(f=>
    firstArray.some(s=> s.v_id == f.v_id));

console.log(result);

To group items by key, you can utilize the reduce method:

const firstArray =
[  { v_id: 3000 },
   { v_id: 3001 },
   { v_id: 3002 }
];

const secondArray =
[  {
      s_id: 'S001', v_id: 3000, type: 'control' },
   {
      s_id: 'S002', v_id: 3001, type: 'mut' },
   {
      s_id: 'S003', v_id: 3001, type: 'mut' },
   {
      s_id: 'S005', v_id: 3001, type: 'control' },
   {
      s_id: 'S008', v_id: 3002, type: 'mut' }
];    

const keys = firstArray.reduce((a, {v_id}) => {
a[v_id] = a[v_id]  || 1;
return a;
}, {});

const allKeys = secondArray.reduce((a, {s_id, v_id, type}) => {
a[v_id] = a[v_id] || {values: []};
a[v_id].values.push({s_id, v_id, type});
return a;
}, {})

Object.keys(allKeys).forEach(k=>{
if( !keys.hasOwnProperty(k))
    delete allKeys[k];
})

console.log(allKeys);

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

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

NodeJS function does not pause for the PostgreSQL database call despite using await keyword

I am attempting to recursively insert entries into the database where each entry depends on the previous one (the ID of the previous entry will be the child_id of the next entry). However, I am facing difficulties in getting async/await to work correctly. ...

DreamFactory's REST API POST request for rest/user/session consistently encounters errors in Internet Explorer 9

In Firefox, Chrome, and Safari, the initial POST rest/user/session request works perfectly fine. However, in Internet Explorer 9, it consistently returns an error. When the dataType is specified as "json," IE9 encounters a 'no transport' error w ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...

Is there a way to determine if a specific key value exists within an array using PHP?

Question: I am trying to determine if a specific value exists as a key within an array in PHP and retrieve the corresponding index. For example, consider the following array: Array ( [0] => Array ( [restaurant_id] => 1519 ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

Using PHP to enhance a select statement to return data when paired with JavaScript

How can I post JavaScript with PHP to enable select statement return? I have a script that is currently functioning as follows: $.post('2.php', { id: 12345 }, function(data) { // Increment vote count, etc }); This is the content of my 2.ph ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

Datatables fails to execute page transitions

It seems like I must be missing something, even though my code is quite basic and closely follows the example provided on the web. I am currently using server-side paging. The issue I'm facing is that upon initial page load, the data from the server ...

Ensure that the footer remains at the bottom of the page without being fixed to the bottom

I am currently working on configuring the footer placement on pages of my website that contain the main body content class ".interior-health-main". My goal is to have a sticky footer positioned at the very bottom of these pages in order to eliminate any wh ...

Deleting array values by their keys in ActionScript

Here are two arrays for you to consider: var valueArr:Array = [50,46,64,85,98,63,46,38,51,24,37,58,48,14,28]; var keyArr:Array = [5,6,7,8,9,10,11,12,13,14]; keyArr: this array contains the keys corresponding to values in valueArr The goal is to remove ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

Is it possible for a memory leak to occur when a jQuery object is created within a function but never actually used?

As an illustration: function calculateTime(minutes) { var newTime = new Date(); newTime.setHours(0, minutes, 0, 0); return angular.element('<input type="hidden"/>').timepicker('setTime', newTime).val(); } I'm cu ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

The Ladda spin animation continues spinning for an additional second after the stop() function is called

I employ the ladda spinner in this manner: var l = Ladda.create(document.getElementById('ladda-test')); l.start(); l.stop(); console.log('ladda is stoped'); The issue I am facing is that following the execution of l.stop(), the animat ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Unable to display Bootstrap 5 modal

I am currently in the process of constructing a basic webpage that includes a navigation bar and a table. The table rows are being dynamically generated through a simple JavaScript script that fetches data asynchronously from a database. I opted to utilize ...