Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example:

Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}]

Array2 = [{id:0, offenceCode: 'JLN14'}, {id:1, offenceCode: 'JLN13'}]

First, I have Array2, and I want to compare the attribute offenceCode with Array1. If they match, I'd like Array1 to return OffenceDesc.

Here's what I've attempted so far:

  demo = [
    {
      offenceCode: 'JLN14',
      offenceType: '7',
      offenceDesc: 'emergency lane abuse'
    },
    {
      offenceCode: 'BRG04',
      offenceType: '8',
      offenceDesc: 'speeding'
    },
    {
      offenceCode: 'CRG04',
      offenceType: '9',
      offenceDesc: 'emergency lane abuse'
    }
  ];

  offenceCode: any;

  ngOnInit() {
    this.offenceCode = this.items.map(x => x.offenceCode1);
    console.log(this.offenceCode);
    if(this.demo.forEach(x => x.offenceCode === this.offenceCode)) {
      // return offenceDesc
    }
  }

I'm currently stuck and unsure how to proceed with solving this issue. You can check out my stackblitz demo. Any suggestions on how to solve this or better practices are much appreciated. Thank you!

Answer №1

Seems like you're searching for:

offenceCode: string[];

ngOnInit() {
  this.offenceCode = this.items.map(x => x.offenceCode1);
  this.demo.forEach(x => {
    this.offenceCode
      .filter(e => e === x.offenceCode)
      .forEach(e => console.log(x.offenceDesc));
    });
}

Made these changes:

  1. You need to declare offenceCode as a string[]
  2. Now, you can iterate through the demo array and filter based on the offenceCode defined earlier. Any matches will be displayed in the console (you can modify this according to your needs)

Answer №2

To achieve this, you can utilize Array.prototype.findIndex.

const findMatchingIndex = this.customArray.findIndex(item => item.code === this.codeToFind);
if(findMatchingIndex !== -1) {
  return this.customArray[findMatchingIndex].description;
}
return undefined;

It's important to remember that the function findIndex will return -1 if no match is found.

Answer №3

function checkOffence(){
  const offences1 = [{code: 'SPE42', description:'Breaking the speed limit'}]
  const offences2 = [{id:0, code: 'SPE42'}, {id:1, code: 'PARK01'}]

  const matchedOffence = offences1.filter(offence1 => 
    offence1.code == offences2.filter(offence2 => 
      offence2.code == offence1.code)[0].code
    )[0]

  return matchedOffence ? matchedOffence.description : null
}

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

Error in material mapping: glDrawElements is trying to access vertices that are out of range in attribute 2

I have developed an algorithm that allows users to input data or a function and then generates a graphical representation of the function. It essentially creates a surface map, similar to the one you can see here. The graphing functionality is working well ...

Warning: The parameter type in the Node JS project is not compatible with the argument type

Upon running this code in WebStorm, I encountered a warning: Argument type {where: {email: userData.emil}} is not assignable to parameter type NonNullFindOptions<Model["_attributes"]> Can someone explain this warning to me? This project ...

Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template). After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mut ...

AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error: TypeError: accountService.logIn(...).success is not a function. The issue lies with ...

Using Javascript to Highlight a Single Row in a Table

Greetings esteemed members of the skilled community at StackOverflow, I must humbly ask for your expertise in solving a dilemma that I am currently facing. The situation is as follows: I have a table generated from an SQL query, and it is crucial for the ...

How can I close the menu when a menu item is clicked in a React.js application?

I am facing an issue where I want to close the menu when clicking on any menu item in React JS. The functionality works fine with a button icon but not with individual menu items. How can I resolve this problem? I have been trying to implement it using CSS ...

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

You cannot click on a React subcomponent

I am currently working on implementing a "Title" component within a header. The idea is that when you click on the title component, a header will appear with various buttons for formatting options such as bold and underline. This concept was inspired by a ...

Angular 5: Ensure Constructor Execution Occurs Prior to Injection

I am working with a file that contains global variables: @Injectable() export class Globals { public baseURL:string; public loginURL:string; public proxyURL:string; public servicesURL:string; constructor(platformLocation: PlatformLocation) { ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

The Append method in FormData is not functioning properly within Angular

I'm facing a challenge in my Angular application where I need to enable image uploads to the server. The issue arises when attempting to add a selected file to the newly created FormData object. Below is the relevant TypeScript component snippet: ima ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Gulp and Vinyl-fs not functioning properly when trying to save in the same folder as the source file due to issues with

After exploring a variety of solutions, I have yet to find success in modifying a file in place using Gulp.js with a globbing pattern. The specific issue I am facing can be found here. This is the code snippet I am currently working with: var fstrm = re ...

Phantom-node failing to return the value from the page.evaluate function

My goal is to extract a specific element from a webpage and save it as an image locally. Here is the node.js code I am using with phantom-node: var phantom = require('phantom'); phantom.create().then(function(ph) { ph.createPage().then(funct ...

What is the correct method for linking resources within the updated Angular 18 workspace using the new "public" directory layout?

Issue Upon creating a workspace using the new @angular/cli@18 package, I encountered difficulty referencing image assets located in the /public folder. In previous workspaces with @angular/cli@17, this was not an issue as they utilized a different asset ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

Error in Node.js React: Unable to add context property as the object is not extendible

Currently, I'm in the process of integrating an isomorphic react component into my node.js + express setup. However, as I attempt to add the component to my jade template for rendering, I encounter this error: TypeError: Can't add property contex ...

Creating a nested JSON structure by fetching data from a remote source

i'm looking to populate the json file located at through a get request. This json contains music from various churches in different cities, with data organized into multiple levels. I want to parse this data using jquery and utilize hidden div elemen ...