What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this:

const products = 
[
    { product: 'prod_aaa', name: 'Starter' },
    { product: 'prod_bbb', name: 'Growth' },
    { product: 'prod_ccc', name: 'Elite' },
];

The second array is a subscriptions array with details of active subscriptions, shown below:

const subscriptions = 
[
    {
        "status":"active",
        "product": "prod_aaa",
        "quantity": 1,
    },
    {
        "status":"active",
        "product": "prod_2342352345",
        "quantity": 1,
    }
];

My goal now is to search the subscriptions array to find the first matching product from the products array, and then display the name of that product (such as Starter/Growth/Elite).

I assume I may need to use subscriptions.filter(), but I am unsure how to extract the name of the matched product.

Although I cannot modify the subscriptions array, I can make changes to the products array if required.

What would be the most effective approach to achieve this task?

By the way, my script is coded in TypeScript.

Answer №1

Using filter() was mentioned, however, it is more suitable when you need to work with the array it returns. In this case, since you're only interested in the name, utilizing a for loop would be more efficient.

const products = [{
    product: 'prod_aaa',
    name: 'Starter'
  },
  {
    product: 'prod_bbb',
    name: 'Growth'
  },
  {
    product: 'prod_ccc',
    name: 'Elite'
  },
];

const subscriptions = [{
    "status": "active",
    "product": "prod_aaa",
    "quantity": 1,
  },
  {
    "status": "active",
    "product": "prod_2342352345",
    "quantity": 1,
  }
];

function find() {
  for (const product of products) {
    for (const subs of subscriptions) {
      if (product.product === subs.product) {
        return product.name;
      }
    }
  }
}

console.log(find())

Edit: If filter() is preferred, here is an alternative approach:

const products = [{
    product: 'prod_aaa',
    name: 'Starter'
  },
  {
    product: 'prod_bbb',
    name: 'Growth'
  },
  {
    product: 'prod_ccc',
    name: 'Elite'
  },
];

const subscriptions = [{
    "status": "active",
    "product": "prod_aaa",
    "quantity": 1,
  },
  {
    "status": "active",
    "product": "prod_2342352345",
    "quantity": 1,
  }
];

let result = products.filter(prod => {
  return subscriptions.some(sub => prod.product === sub.product)
})[0].name;

console.log(result)

Answer №2

Instead of following Avneesh's method, I decided to start by going through the subscriptions array.

// Look for the first subscription where the product is also in the products array.

let requiredSub = subscriptions.find(sub => products.some(p => p.product === sub.product))

let requiredProduct = requiredSub.product

For more information on using the Javascript Array.some method, check out the MDN reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

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

I am unable to retrieve values from the req.body object in Node.js

Can anyone assist with node.js? I am having trouble accessing the values in my req.body object. Here is how it is populated: { '{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a060e0b270f0814130906 ...

What is the process for inserting a watermark onto an image as it is being retrieved from Firebase?

I am developing a React website where I need to implement a feature that adds a watermark to an image when it is retrieved from Firebase storage. Is there a way to apply a watermark while accessing the image from the storage? I have already looked into Ho ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: https://i.sstatic.net/ErbDD.png Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetic ...

Strange JSON.parse quirk observed in Node.js when dealing with double backslashes

My coworker encountered an issue while trying to parse a JSON string from another system, leading to unexpected behavior. To illustrate the problem, I have provided a simple code snippet below: // This code is designed for node versions 8 and above con ...

In node.js, the global variable fails to update within a while loop

I need to store data in an array every 5 seconds. My initial approach was: setInterval(function() { data.push({ price: getCurrentPrice(), time: moment().format() }) }, 5000); However, after running for exactly half an hour, the s ...

Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel). However, when I include the last c ...

Prevent removal of h2 tag within a contenteditable segment

Can a section be made permanent within a contenteditable element to prevent user removal? I have an h2 tag inside a contentEditable div. I do not want the user to be able to edit the h2 tag, so I set contentEditable=false, but they can still select and de ...

Utilizing HTML/CSS with React/Bootstrap: A Comprehensive Guide

Looking for help with integrating HTML/CSS code into React/Bootstrap? I need assistance with coding in React using Bootstrap. How do I effectively use components and props? Even after installing bootstrap, I am encountering errors. Is it possible to dire ...

Forecast the width of an element using JavaScript

Is there a way to display tab elements on a webpage without them automatically wrapping into a new row if there are too many? Instead, I would like an arrow icon to appear at the end of the tabs so users can cycle between tab groups. The challenge is that ...

Identifying overflow of text or elements in JavaScript during execution

The website I'm working on has a unique design that requires users to scroll horizontally using the Arrow Keys instead of swiping. To achieve this, I must constantly check for overflow in text or elements each time a new page is loaded, and if necessa ...

Having difficulty rendering image in vueJS

I am currently using the SideMenu component to display other SideMenuButton components, but I'm facing an issue where the image is not appearing. Here are the code snippets for both components: SideMenu: <template> <div id = "side-m ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...

local individuals and local residents (duplicate) dispatched from the server

Upon analyzing my server's response, I have observed a duplicate of my locals within the locals object. Here is an example: Object { settings: "4.2", env: "development", utils: true, pretty: true, _locals: { settings: ...

What could be causing the custom aside or slide panel to not slide properly when using Angular Strap?

I recently tried creating a slide panel and came across the Angular Strap library. After studying the documentation, I attempted to implement the slide panel using this library. However, I encountered an issue where my side panel did not slide as demonst ...

The map function is selectively applied to certain expressions, not all

Currently, I am attempting to display the genre Name and its corresponding gradient by utilizing the map function over an array called genres. While the map function successfully renders the genre Name, it seems to return the same component for the genre g ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...

Triggering on multiple clicks - MULTIPLE CLICKS

I'm currently in the process of developing a website and I have a specific requirement where I need an image to change on click to another image, and then to a third image on the second click, and so forth. I've managed to create a JavaScript fu ...

Angular 2's abstract component functionality

What are the benefits of utilizing abstract components in Angular 2? For example, consider the following code snippet: export abstract class TabComponent implements OnInit, OnDestroy {...} ...