typescript array filter attributes

I encountered a situation where I had 2 separate arrays:

  items = [
    {
      offenceType:"7",
      offenceCode:"JLN14",
    }, 
    {
      offenceType:"48",
      offenceCode:"JLN14",
    }
  ];



  demo = [
    {
      offenceCode: 'JLN14',
      offenceType: '7',
      offenceDesc: 'emergency lane abuse'
    },
    {
      offenceCode: 'JLN14',
      offenceType: '48',
      offenceDesc: 'speeding'
    },
    {
      offenceCode: 'JLN13',
      offenceType: '52',
      offenceDesc: 'parking abuse'
    }
  ];

I needed to filter certain attributes between these 2 arrays. For example, in the items array, there are offenceType and offenceCode values which need to be compared with the demo array that contains offenceType, offenceCode, and offenceDesc. If both offenceType and offenceCode match, then I need to retrieve the offenceDesc from the demo array. Here is the approach I tried based on my research:

  newArray = [];

  // create new array to map 2 objects
  this.items.forEach(x => {
    this.newArray.push(x.offenceCode, x.offenceType);
    console.log('newArray',this.newArray);
    // doing filter
  })

Here is a link to my stackblitz demo

Previously, I asked a similar question on Stack Overflow but I couldn't find a solution even after multiple attempts. Being new to coding, I would appreciate any suggestions on how to solve this problem.

Answer №1

Utilize a map function

const items = [
  {
    offenceType:"7",
    offenceCode:"JLN14",
  }, 
  {
    offenceType:"48",
    offenceCode:"JLN14",
  }
];

const demo = [
  {
    offenceCode: 'JLN14',
    offenceType: '7',
    offenceDesc: 'emergency lane abuse'
  },
  {
    offenceCode: 'JLN14',
    offenceType: '48',
    offenceDesc: 'speeding'
  },
  {
    offenceCode: 'JLN13',
    offenceType: '52',
    offenceDesc: 'parking abuse'
  }
];

const newArray = items.map(item => {
   const lookup = demo.find(i => item.offenceType === i.offenceType);
   return {
     offenceType: lookup.offenceType,
     offenceCode: lookup.offenceCode,
     offenceDesc: lookup.offenceDesc
   }
});

console.log(newArray);

Answer №2

To get the offense description, create a function that searches for it and then apply the function using map on the items


const offenses = [
  {
    offenseType:"7",
    offenseCode:"JLN14",
  }, 
  {
    offenseType:"48",
    offenseCode:"JLN14",
  }
];

function findOffenseDescription(item) {
    const offenseData = [
        {
          offenseCode: 'JLN14',
          offenseType: '7',
          offenseDescription: 'emergency lane abuse'
        },
        {
          offenseCode: 'JLN14',
          offenseType: '48',
          offenseDescription: 'speeding'
        },
        {
          offenseCode: 'JLN13',
          offenseType: '52',
          offenseDescription: 'parking abuse'
        }
      ];
      const match = offenseData.find(offense => offense.offenseCode === item.offenseCode && offense.offenseType === item.offenseType);
      return match && match.offenseDescription;
}

const newOffensesArray = offenses.map(findOffenseDescription);
console.log(newOffensesArray); // [ "emergency lane abuse", "speeding" ]

Answer №3

Another method that can be used is filter and map in order to extract the desired offenceDesc information.

const offenseDescriptions = data.filter(
    element => items.find(item => item.offenseCode === element.offenseCode
                         && item.offenseType === element.offenseType))
    .map(value => value.offenseDesc)

Answer №4

To implement negated logic, utilize the every() method.

Check out the relevant code snippet:

...

  newArray = [];

  constructor() { }

  ngOnInit() {
    let  foundOffence: any;

    this.items.forEach(itemsOffence => {
      this.demo.every(demoOffence => {
        let isNoMatch: boolean = demoOffence.offenceCode != itemsOffence.offenceCode || demoOffence.offenceType != itemsOffence.offenceType;
        foundOffence = isNoMatch? undefined: demoOffence;
        return isNoMatch;
      })
      if (foundOffence) {
        console.log(`foundOffenceDesc = ${foundOffence.offenceDesc}`);
        this.newArray.push(foundOffence);
      }
    })
    console.log("newArray = ", this.newArray);
  }

...

Observe this functionality in action through the following StackBlitz demo

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

Rerendering of a React component occurs upon a change in its state

Previously, my form was functioning flawlessly. However, after making a few modifications to the state variables, the input field now loses focus upon a state change. I am utilizing MUI and everything was working perfectly until this sudden issue arose f ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

The function is triggered only on resize, not on initial load

Is there a way to ensure that the carouselPartialView function runs automatically when the page loads? I've noticed that it doesn't run when directly called, but works fine when called with the resizeWitdthOnly function. How can I make sure it ru ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

Aliases in Typescript are failing to work properly when used alongside VSCode Eslint within a monorepository

I've incorporated Typescript, Lerna, and monorepos into my current project setup. Here's the structure I'm working with: tsconfig.json packages/ project/ tsconfig.json ... ... The main tsconfig.json in the root directory looks lik ...

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

Unable to send a String to the controller via ajax

Exploring web development using play framework and ajax. I'm looking to pass a string from a form to a controller using ajax, but unsure of how to go about it. Can anyone assist me with this? Here's my code snippet: html: <form onsubmit="retu ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Can the details of a package be retrieved from a Nuget private store using a REST API?

Currently working on an Angular 8 project that involves displaying the details of Nuget packages from a custom store. I am wondering if it is possible to retrieve package details from an NPM custom store using a REST API? Something similar to: https://lea ...

Refresh the dataTable following the form submission within the colorbox

On my page test.php, I am using jQuery DataTables to fetch data. There is a button labeled "Add Note" that opens an ajax form inside colorbox. The form submission process is functioning correctly, but I am looking for a way to refresh the DataTables when a ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Retrieve information from an ajax call within an Angular application

I need assistance with 2 requests I have. $.ajax({ type: "POST", url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token", data: "grant_type=client_credentials", headers: { 'Content-Type': 'application/x-www-form-urlencoded&a ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

Extending Mongoose's capabilities with header files for the "plugin" feature, utilizing the .methods and .statics methods

My task is to develop Typescript header files for a script that enhances my Mongoose model using the .plugin method. The current signature in the Mongoose header files looks like this: export class Schema { // ... plugin(plugin: (schema: Schema, opt ...

Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the follo ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

Exploring the world of jQuery sliders and dynamically updating div container content

Alright, here's what I have come up with so far: First, take a look at this website to see the idea I am trying to explain: What I am aiming for is this concept: A visitor goes to the provided website and wants to know what type of sandwich they can ...