Leveraging TypeScript to sort and extract specific elements from two arrays

Given two arrays, I am looking to identify the elements in array2 that match elements in array1 based on a specific property.

The arrays are structured as follows:

var array1 = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"},
    {"myId": 3, "text": "d"},
    {"myId": 4, "text": "e"},
    {"myId": 5, "text": "f"}];


var array2 = [
    {"myId": 1, "value": "1x1"},
    {"myId": 1, "value": "2x2"},
    {"myId": 2, "value": "3x3"},
    {"myId": 6, "value": "4x4"},
    {"myId": 7, "value": "5x5"}];

I aim to extract the objects from array1 that have matching myId values in array2.

The expected output should be an array like this:

var result = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"}];

I have experimented with filter and include methods but have not been able to achieve the desired outcome yet.

Answer №1

If you want to extract all the myId values from array2, and then use those values to filter out elements in array1, you can follow this approach:

const array1 = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"},
    {"myId": 3, "text": "d"},
    {"myId": 4, "text": "e"},
    {"myId": 5, "text": "f"}];


const array2 = [
    {"myId": 1, "value": "1x1"},
    {"myId": 1, "value": "2x2"},
    {"myId": 2, "value": "3x3"},
    {"myId": 6, "value": "4x4"},
    {"myId": 7, "value": "5x5"}];
    
const ids = new Set(array2.map(item => item.myId));
const filteredArray1 = array1.filter(item => ids.has(item.myId));
console.log(filteredArray1);

Answer №2

If you're looking for a way to filter arrays based on certain criteria, there are two approaches you can take depending on your needs.

var array1 = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"},
    {"myId": 2, "text": "c2"}, // not an exact match
    {"myId": 3, "text": "d"},
    {"myId": 4, "text": "e"},
    {"myId": 5, "text": "f"}
 ];


var array2 = [
    {"myId": 1, "value": "1x1"},
    {"myId": 1, "value": "2x2"},
    {"myId": 2, "value": "3x3"},
    {"myId": 6, "value": "4x4"},
    {"myId": 7, "value": "5x5"}];
    

let result = array1.filter(a => array2.some(b => a.myId == b.myId))

console.log(result)

If you require an exact match instead:

var array1 = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"},
    {"myId": 2, "text": "c2"}, // exact match
    {"myId": 3, "text": "d"},
    {"myId": 4, "text": "e"},
    {"myId": 5, "text": "f"}];


var array2 = [
    {"myId": 1, "value": "1x1"},
    {"myId": 1, "value": "2x2"},
    {"myId": 2, "value": "3x3"},
    {"myId": 6, "value": "4x4"},
    {"myId": 7, "value": "5x5"}];
    
function filterForId(arr1, arr2) { 
  let filtered = []
  return arr1.filter(a => {
    let found = arr2.find(b => !filtered.includes(b) && a.myId == b.myId);
    if (found) { filtered.push(found); return true; }
    return false;
  });
}

let result = filterForId(array1, array2);

console.log(result)

Answer №3

Could this work, even though the performance could potentially be poor?

array1.filter((item) => array2.some((el) => item.myId === el.myId))

Answer №4

let data1 = [
    {"myId": 1, "text": "a"},
    {"myId": 1, "text": "b"},
    {"myId": 2, "text": "c"},
    {"myId": 3, "text": "d"},
    {"myId": 4, "text": "e"},
    {"myId": 5, "text": "f"}];

let data2 = [
    {"myId": 1, "value": "1x1"},
    {"myId": 1, "value": "2x2"},
    {"myId": 2, "value": "3x3"},
    {"myId": 6, "value": "4x4"},
    {"myId": 7, "value": "5x5"}];
    
const results = [];

for (const el of data1) {
  const idExistsInData2 = data2.find(a => a.myId === el.myId);
  if (idExistsInData2) {
    results.push(el);
  }
}

console.log(results)

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

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

I'm looking to center the column content vertically - any tips on how to do this using Bootstrap?

Hello! I am looking to vertically align the content of this column in the center. Here is an image of my form: https://i.stack.imgur.com/nzmdh.png Below is the corresponding code: <div class="row"> <div class="form-group col-lg-2"> ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Problem with clicking on items in Slick Slider Variable width menu once they reach the end

Is there a way to stop the slick slider with variable width items from scrolling after reaching the last item? I am encountering this issue where it continues to scroll even after the end. If you want to see the problem in action, check out this fiddle: h ...

Transmit information from a bean to JavaScript using JSON in JavaServer Faces

I need help transferring my arraylist from a managedBean to JavaScript code. The bean code is shown below: public void getDataAsJson(){ String [] dizi={"Tokyo","Jakarta","New York","Seoul", "Manila","Mumbai","Sao Paulo","Mexico City", ...

Challenge with Transferring Data to be Displayed

My issue lies in calling a function with 3 inputs - 2 numbers and 1 string. The two numbers are being passed correctly, but I need the string to be printed within the element. I suspect the problem is related to passing the parameter to an HTML part of th ...

After performing the `ng build --prod` command in Angular 4, deep linking functionality may not

I have a requirement to display different screens in my Angular application based on the URL pasted by the user in the browser: http://localhost/screen1 (should show screen1) http://localhost/screen2 (should show screen2) To achieve this, I have set up ...

Enhancing a node.js application with express()

I am currently utilizing Express MVC with node.js. The primary object I am working with is express(), which is assigned to an alias called app: var express = require('express'); app = express(); Is there a way for me to expand the functionali ...

Switching between different elements in an array using React

I've got a collection of appointments and I need to create a React view that will show them one by one. Users should be able to navigate through the appointments using arrow buttons. Here's an example of what the data looks like: const arr = [ ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...

NodeJS is constantly refreshing the data in the database table

Every day, I use a cron job to scrape data and insert it into a database. However, I'm facing an issue where the database results on the server do not refresh themselves after new data is inserted. I've come across 2 solutions here, but one was ...

Jquery is not working as expected

I am having trouble implementing a jQuery function to show and hide select components. It doesn't seem to be working correctly. Can someone help me identify the issue? <html> <head> <meta charset='UTF-8' /> <script ...

Calculate the total occurrences of events within a Python array

I am working with the following array: arr = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0] In Python, I need to determine how many events are present in the array. An event consists of a single '1' or a series of consecutive &apos ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Issues with rendering AngularJS onto an HTML page are currently being experienced

I was attempting to learn AngularJs in order to improve my front-end development skills, but unfortunately I ran into some issues. Despite following the video tutorials on their site step by step, I couldn't get it to render correctly. Here's the ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

I'm having trouble making a Javascript ajax request to my Web API controller page. It seems like I just can't figure out the correct URL

Currently, I am facing an issue with my registration page where I am attempting to save input fields into a new record in the Users table. <button class="btn-u" type="submit" onclick="submitclicked()">Register</button> The click event trigger ...

The term 'sequelize' is missing its definition - it involves Sequelize and consign

Just starting out in the world of Node.js. I'm currently working on integrating Sequelize into a basic application with Consign. In my "config/db.js" file: var Sequelize = require('sequelize'); var sequelize = new Sequelize('test&ap ...

Uploading multiple strings to an Amazon S3 bucket using Node.js by piping a string

Suppose I have a simple loop similar to the one shown below: for (const i=0; i<3; i++) { to(`This incrementer is ${i}`) } At the end of the loop, I expect my file to contain: This counter is 0 This counter is 1 This counter is 2 I at ...