Discover the best method for sorting an array into a new array using Angular

const arr1 = [
  {
    id: "c1",
    section: {
      name: "emerald",
      room: { id: "r1", name: "Room 1" }
    }
  },
  {
    id: "c2",
    section: {
      name: "diamond",
      room: { id: "r2", name: "Room 2" }
    }
  },
  {
    id: "c3",
    section: {
      name: "gem",
      room: { id: "r3", name: "Room 4" }
    }
  },
  {
    id: "c4",
    section: {
      name: "pearl",
      room: { id: "r5", name: "Room 5" }
    }
  }
];

const arr2 = [
  {
    name: "diamond",
    room: { id: "r2", name: "Room 2" }
  },
  {
    name: "gem",
    room: { id: "r3", name: "Room 4" }
  }
];

The expected result should show:

[{
        id: "c2",
        section:{
            name: 'diamond',
            room: {id: "r2", name: "Room 2"}
        }
    },{
        id: "c3",
        section:{
            name: 'gem',
            room: {id: "r3", name: "Room 4"}
        }
    }];

I am trying to filter one array to another using the filter method, but it's not working as expected. Here is the code I attempted:

arr1.filter((x: any) => [arr2.room.id].includes(x.section.room.id))

This code is not producing the desired output. My intention is to filter out elements from arr1 that do not exist in arr2 by comparing their room IDs.

Answer №1

Here is the solution you've been searching for:

const filterArr = mainArray.filter((item) => secondaryArray.findIndex(subItem => subItem.id === item.id) !== -1);

Make sure to loop through the second array to achieve this.

Answer №2

const elementsArray = [{
    id: "e1",
    group: {
      name: "apple",
      category: {
        id: "c1",
        label: "Fruit"
      }
    }
  },
  {
    id: "e2",
    group: {
      name: "banana",
      category: {
        id: "c2",
        label: "Fruit"
      }
    }
  },
  {
    id: "e3",
    group: {
      name: "carrot",
      category: {
        id: "c3",
        label: "Vegetable"
      }
    }
  },
  {
    id: "e4",
    group: {
      name: "kiwi",
      category: {
        id: "c4",
        label: "Fruit"
      }
    }
  }
];

const filterArray = [{
    name: "banana",
    category: {
      id: "c2",
      label: "Fruit"
    }
  },
  {
    name: "carrot",
    category: {
      id: "c3",
      label: "Vegetable"
    }
  }
];

let namesArray = filterArray.map(function(item) {
  return item.name;
})

const filteredElements = elementsArray.filter(function(elem) {
  return namesArray.includes(elem.group.name);
});

console.log(filteredElements);

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

Tips for dynamically displaying Angular Material tags within an Angular component using JSON data

I received a JSON response structured like this: { _id: '5dd0d0dc4db1cf9c77781aaa', picture: 'http://placehold.it/32x32', name: 'Graciela Mcmahon', guid: '98c0fcc2-1dfc-4974-bdae-d8263d783e0a&ap ...

Transmitting JSON information using post method through .ajax(), as well as receiving a JSON reply

Seeking assistance with debugging a registration page I am currently coding. I have hit a roadblock for the past 48 hours and would greatly appreciate any help in resolving the issues. CHALLENGE I am utilizing JavaScript to validate form inputs for error ...

Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows: ERROR Error: Uncaught (in promise): NullInj ...

Create a full type by combining intersecting types

I have multiple complex types that are composed of various intersecting types. I am looking to extract these types into their final compiled form, as it would be useful for determining the best way to refactor them. For example, consider the following: ty ...

How can I pass a PHP variable to a JavaScript variable using PHP and JQuery/JavaScript?

I am facing a challenge with a large <select> input that is used across multiple pages. My idea is to separate this dropdown box into its own PHP file and load it externally using JQuery. Is this approach feasible? Here's an outline of what I ha ...

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 ...

Data Malfunction Leads to Failure of Ajax POST Request in Client-Side Operation

I am facing an issue where my Ajax POST calls are failing when I attempt to assign complex JavaScript objects to the [data] key/value pair after using JSON.stringify() for serialization. Could anyone advise on what additional ajax call configuration is re ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Guide on Adding Tawk.to Widget to Your Next.JS Website

I followed the instructions on their @tawk.to/tawk-messenger-react plugin documentation, but I am still facing issues. I created a component named /components/Chat.js import TawkMessengerReact from "@tawk.to/tawk-messenger-react"; export defaul ...

Diverse Form in the Typescript Language

Two functions need to be created to bind to two buttons, each with slight variations in one string. const onClickLoginA = (): void => { const loginURI = `http://.../.../A`; window.open(loginURI, `Login with A`); } const onClickLoginB = (): void =& ...

Please anticipate the completion of data loading

I need help adding a custom tweet button to my Angular application. Below is the code I am using: HTML: <a href="" class="retweet" retweet target="_blank" data-info="{{ data.name }}"> Tweet </a> JS: myApp.directive('retweet', ...

The global coordinate system is used to determine the direction of raycasting, not the local coordinate

Using the raycasting method to detect various colored strips on both sides of the track, I am able to keep my car object in position by calculating the distance. However, the issue lies in the fact that the ray always points in a constant direction in the ...

What are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...

Incorporating a delete button onto an image using JavaScript

I am currently developing a BlogApp and facing difficulty in attempting to include a button on an image. The image is being retrieved from the Django database in JavaScript (HTML). My goal is to have a clickable button overlaid on the image. views.py def ...

reducing the dimensions of the expanding panel in Material UI

I am facing a challenge which requires me to reduce the size of the expansion panel when it is open or expanded. I checked the elements and styles tab, but it seems that we need to override the styles. Has anyone dealt with this scenario before? Here is a ...

How can I attach the input value that has been selected to another div using Ajax AutoComplete for jQuery?

Greetings, I am currently utilizing the Ajax AutoComplete for jQuery library. Within this library, there are 2 demos available. In the first demo titled "Ajax auto-suggest sample (start typing country name)", when a country is selected from the dropdown, ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

Performing an Ajax call in the correct order within an MVC framework

One challenge I face is ensuring that my series of Ajax calls to call stored procedures and load partial views always fire in the correct order. Sometimes, they do not fire as expected due to timing issues. How can I guarantee that these Ajax calls execu ...