Remove elements from an array in Typescript if they are not present in a nested array

I am struggling with filtering values from a single-dimensional array based on id matches in an array of objects.

array1 = [1, 3, 15, 16, 18];

array2 = [
       { id: 1, dinner : pizza },
       { id: 15, dinner : sushi },
       { id: 18, dinner : hummus }
]

My goal is to remove values from array1 that don't have a matching id in array2.

While I know how to filter two single-dimensional arrays, I'm having trouble adapting the code for this scenario involving an array of objects.

const array1 = array1.filter(id => array2.includes(id));

If anyone has any insight or suggestions, please share them. Thank you!

Answer №1

These two arrays consist of single dimension elements.

To eliminate numbers from array1 that do not match any of the ids in the objects within array2, you can combine the .some() and .filter() functions.

const array1 = [1, 3, 15,16,18];
const array2 = [
    { id: 1, dinner : 'pizza' },
    { id: 15, dinner : 'sushi' },
    { id: 18, dinner : 'hummus' }
]

const filteredArr = array1.filter(v => array2.some(o => v == o.id));

console.log(filteredArr);

Answer №2

If you want to extract specific IDs and filter them, you can follow the below steps:

var array1 = [1, 3, 15, 16, 18];

var array2 = [
       { id: 1, dinner : "pizza" },
       { id: 15, dinner : "sushi" },
       { id: 18, dinner : "hummus" }
]

const Ids = array2.map(i=> i.id);
var res = array2.filter(i => Ids.includes(i.id)); 
var res2 = Ids.filter(i => array1.includes(i))// Or, just to get common Ids

console.log(res)
console.log(res2)

Alternatively, using reduce can help you achieve the same result without making two passes:

var array1 = [1, 3, 15, 16, 18];

var array2 = [
       { id: 1, dinner : "pizza" },
       { id: 15, dinner : "sushi" },
       { id: 18, dinner : "hummus" }
]

var res = array2.reduce((acc, {id})=>{
  if(array1.includes(id)){
   acc = [...acc, id]
  }
  return acc
},[]);

console.log(res)

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

Unable to save array in global variable using Ajax, constantly receiving undefined

I'm attempting to store an array obtained from an ajax call in a global variable so that I can access it later, but I keep encountering an undefined error. <script> var items = []; function add(value){ items.push(value); ...

Exporting modules in TypeScript allows developers to encapsulate code into

Can you provide the TypeScript equivalent of this code snippet? export default (app, passport) => { function ... } ...

Determining which data is retrieved from a database based on a specific field using Sequelize and MySQL

I'm looking to retrieve the most recent records from a database, organized by category. My goal is to fetch 20 records, with 5 of the latest posts in each category. I want to ensure that the result consists of 20 total records, evenly distributed amon ...

I'm experiencing unexpected behavior with the <form> element in React, it's not functioning as I

I have encountered a strange behavior while trying to implement a form element for user input. When I directly insert the form element, everything works perfectly fine as I type in the letters. However, if I insert the form element through the AddForm comp ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Assistance needed for JavaScript link substitution

As I am wrapping up the web application version of my website, I have encountered a small issue. I need to convert the <script> var a=document.getElementsByTagName("a"); for(var i=0;i<a.length;i++) { a[i].onclick=functio ...

Executing a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code: cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) { 'use strict'; var exec = require('cordova/exec'); var sms = {}; functio ...

Constant Initialized Array of Structures within a C++ Class

When working with const arrays in a class namespace in C++, there is a limitation where you cannot define them as private. For example: class c { private: struct p { int a; int b; }; static const p pp[2]; }; const c::p pp[2] = { {1,1},{2 ...

Jest Test - Uncaught TypeError: Unable to create range using document.createRange

my unique test import VueI18n from 'vue-i18n' import Vuex from "vuex" import iView from 'view-design' import {mount,createLocalVue} from '@vue/test-utils' // @ts-ignore import FormAccountName from '@/views/forms/FormAcco ...

The loop is not fully completing all actions during the first iteration

While working on a multiple upload feature using the Multiple_upload library in CodeIgniter, I encountered an issue where the loop that generates thumbnails only runs on the first iteration. Here is the relevant code snippet: function saveContentImages() ...

Looking to extract data from an HTML form?

In my HTML form, I am dynamically creating elements and setting their name and value attributes. When I try to access the value using document.formname.nameoftheelement.value, I receive an error stating that the value is undefined. I then attempted to us ...

Any ideas on how to potentially establish a default route based on conditions with react-router-dom v6?

Managing two pages, Page1 and Page2, requires conditional configuration for setting one as the homepage based on a specific condition. Additionally, all URLs must be prefixed with an ID. Take a look at the code snippet below: <Routes> <Route pat ...

What made the "in" operator not the best choice in this situation?

When I set out to create a type that represents the values of a given object type, I initially came up with this: type Book = { name:string, year:number, author:string } // expected result "string" | "number" type ValueOf<T ex ...

What is the best way to retrieve a particular variable from an ng-repeat loop?

I'm currently working on a task where I have an ng-repeat loop that generates multiple dropdowns. Each dropdown is associated with a unique ID generated by the controller for reference purposes. The issue I am facing is that when a user selects an op ...

Tips for addressing the error message "Cannot PUT /":

I have been working on updating a local database using MongoDB for my project. Here is the code snippet I am using to update the data. The second part involves editing that redirects the updated data. I am not encountering any errors, so I am unable to i ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

Difficulty encountered while executing JavaScript in Chrome 78 with Python and Selenium, as pages are not switching

I have encountered an issue with my script that switches between site pages containing tables. Everything was working smoothly for months with Chrome version 76, but after updating to the new Chrome version 78.0.3904.70, an error has arisen: driver.execu ...

Optimizing Array Comparison in JavaScript and Angular 2

In my Angular 2 .ts (TypeScript) file, I have declared two arrays as shown below: parentArray: Array<Model> initialized with {a, b, c, d} modifiedArray: Array<Model> modified with data {c, e, f, g} How can I efficiently determine the differ ...

Attempting to rearrange the table data by selecting the column header

In an attempt to create a table that can be sorted by clicking on the column headers, I have written code using Javascript, HTML, and PHP. Below is the code snippet: <?php $rows=array(); $query = "SELECT CONCAT(usrFirstname,'',usrSurname) As ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...