How to use TypeScript to filter an array based on the values of another array

Suppose I have two arrays. The first one looks like this:

names: [{
  value: 'recordedData',
  desc: 'Data'
} {
  value: 'recordedNumbers',
  desc: 'numbers'
} {
  value: 'recordedNames',
  desc: 'names'
}]

And the second array is as follows:

displayed: [{
  value: 'data',
  desc: 'Data'
} {
  value: 'numbers',
  desc: 'numbers'
}]

I aim to filter the first array using the criteria from the second array, resulting in:

DisplayedNames: [{
  value: 'recordedData',
  desc: 'Data'
} {
  value: 'recordedNumbers',
  desc: 'numbers'
}]

Answer №1

A clever technique to accomplish this is by utilizing Array.prototype.filter() and Array.prototype.some()

const items = [{value: 'recordedData', desc: 'Data'},
 {value: 'recordedNumbers', desc: 'numbers'},
 {value: 'recordedNames', desc: 'names'}];
 
const displayItems = [{
  value: 'data',
  desc: 'Data'
}, {
  value: 'numbers',
  desc: 'numbers'
}]

 const finalResult = items.filter(x => displayItems.some(y => y.desc === x.desc));
 
 console.log(finalResult);

Learn more about how Array.prototype.some() works - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some Find out more about Array.prototype.filter() here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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

Breaking Down and Optimizing your Code with Destructuring and

Currently, I am performing some basic destructuring in Javascript: //@flow "use strict"; (function(){ const {a,c} = check(true); })(); function check(bool:boolean):{|a:string,c:string|}|{||}{ if(bool){ return { a:"b", c:"d" } ...

Eliminate all key-value pairs from an array of objects except for the specified key-value pair

I've got an array filled with objects const myArr = [ {k1: 1, k2: 1, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4} ] I'm attempting to filter these objects, although I don&apos ...

MongoSearch: A Geo-Targeted Search Engine tailored to your needs

For my new app project, I am using MongoDB, Express, JS, and Node to create a platform similar to Yelp. After some research, I discovered how to search for multiple fields within a campus schema (including campuses, restaurants, barbershops, and names). No ...

Searching for a substring within a larger string in JavaScript

I am trying to create a loop in JavaScript (Node.js) that checks if a string contains the "\n" character and then splits the string based on that character. <content>Hello </content><br /> <content>bob </content><br / ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

Typescript error: Cannot assign type 'undefined' to type 'string | number | symbol'

I need help figuring out how to address a TypeScript error in my code. Here's the scenario: export type status = 'success' | 'error' | undefined; There is an object that maps to different icons based on the status. const iconsMap: ...

When using JQuery, data may not be displayed in another function even when using the same command

Hello, I'm new here and encountering a strange problem with two functions in my script. Let me show you the first function: $(document).on("click", "#result2 p", function(){ var inv_id = $(this).text(); $.get("autocomplete_inv.php", ...

importance of transferring information in URL encoded form

Recently, I started learning about node.js and API development. During a presentation, I was asked a question that caught me off guard. I had created a REST API (similar to a contact catalog) where data was being sent through Postman using URL encoded PO ...

Assign a variable name to the ng-model using JavaScript

Is there a way to dynamically set the ng-model name using JavaScript? HTML <div ng-repeat="model in models"> <input ng-model="?"> </div JS $scope.models= [ {name: "modelOne"}, {name: "modelTwo"}, {name: "modelThree"} ]; Any ...

Implementing Login using Google in a Nativescript iOS application: A step-by-step guide

I've been working on implementing Google's ID provider login in Nativescript using the nativescript-social-login plugin. While it works smoothly on Android, I've hit a roadblock with iOS. Following the instructions from the plugin creator, ...

Guide user to different screen in React Navigation depending on context state

In my project, I have introduced a new state called roleSelected. Initially, the value of this state is set to false, and it is managed within my AuthContext. const [roleSelected, setRoleSelected] = useState(false); The configuration of my stack navigatio ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Is there a way to deactivate keyboard input on an HTML number input field? How about in a React or Material-UI environment?

I am working with an <input> tag that has the attribute type="number", and I want to disable keyboard input so that users are required to adjust the value using the spinner (up and down arrows). This will allow me to consume the input value on each c ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

What is the best way to emphasize a table row during a search rather than just the text?

I am currently using a jQuery script that searches for a specific string in a simple text input field and highlights only the string itself if it is found. However, my data is organized within a table and I am interested in knowing if it is possible to hig ...

Using jQuery to send data with an AJAX post request when submitting a form with

This is the code I'm working with: <html> <body> <?php include('header.php'); ?> <div class="page_rank"> <form name="search" id="searchForm" method="post"> <span class="my_up_text">ENTER THE WEBSITE TO ...

Develop a universal function for inserting information into an array within a data set

I need assistance with my Typescript code. I am currently working on a method that pushes data into an array in a mongoose collection. However, the issue I'm facing is that the value is not being passed dynamically to the Key field in the $set operato ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...

Detecting the existence of a scrollbar within the document object model using JavaScript - a guide

Could someone provide a JavaScript syntax for detecting the presence of a scrollbar in the DOM by measuring the body height and window height? ...

Tips on dynamically translating resources using ngx-translate

Can anyone help me with ngx-translate? I'm struggling to figure out how to dynamically translate resources in HTML. Here's an example: "agreement.status.0": "New", "agreement.status.1": "Rejected", ...