Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering.

The arrays in question are:

const array1 = [a, b, c, d]

The array to be filtered based on matching 'id' values from array1 is:

const array2 = [
{
   id: b
   title: title1
},
{
   id: d
   title: title2
},
{
   id: f
   title: title3
}
]

Answer №1

A simple method is to utilize a pair of nested for-loops, although it may not be the most efficient option.

res = [];
for (var i = 0;i<array1.length;i++) {
    for (var j = 0;j<array2.length;j++) {
        if (array1[i] == array2[j].id) {
            res.push(array2[j]);
             break;
        }
    } 
}

Answer №2

To filter an array based on another array, you can utilize Array.prototype.filter() along with Array.prototype.indexOf():

const primaryArray = ['a', 'b', 'c', 'd'];

const secondaryArray = [{
   id: 'b',
   title: 'title1'
}, {
   id: 'd',
   title: 'title2'
}, {
   id: 'f',
   title: 'title3'
}];

const filteredResult = secondaryArray.filter(function(item){
    return primaryArray.indexOf(item.id) !== -1;
});

Answer №3

Make sure to add this missing '' when using the filter and includes methods with Arrays.

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [
    {
       id: 'b',
       title: 'title1'
    },
    {
       id: 'd',
       title: 'title2'
    },
    {
       id: 'f',
       title: 'title3'
    }
]

const result = array2.filter(({id}) => array1.includes(id));
console.log(result);

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

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Incorporating Dynamic Javascript: A Step-by-Step Guide

I came across a select object that looks like this: <select id="mySelect" onchange = "start()" > <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> < ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Obtaining the MasterTableView Edit Form within a Radgrid to acquire a reference to a textbox

Can anyone help me with two things, please? I am struggling to access the currently edited existing row in the Radgrid and also the index of the Edit form when attempting to add a new record to the table. function OnClientSelectedIndexChanged(sen ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

Performing a repeated action to choose each item from a dropdown menu

I attempted to streamline the process by creating id tags for each dropdown and implementing a loop to select each manufacturer without having to write an extensive amount of code. However, I encountered difficulties and was unable to find a solution. The ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

Having trouble using functions with dynamically loaded content via AJAX in JQuery

I am facing an issue with my code. I am trying to dynamically fetch some data and display it. I have checked the request using firebug and it seems to be successful, but the problem arises when I try to execute the activeImage() function. The images are no ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Try uploading a file with the imageUpload function in JavaScript, could be something basic

Today I successfully uploaded a picture using a basic button (id: "imageUpload") to select and upload a file. Everything worked flawlessly, with the thumbnail of the picture appearing in "thumb1." Now, I am attempting to allow users to upload a picture by ...

Switch up the box-shadow color with ColorThief!

Is there a way to adjust this script to change the box-shadow color of #player1? <script type="text/javascript> $(window).ready(function(){ var sourceImage = document.getElementById("art"); var colorThief = new ColorThief(); var color = ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

Guide on deploying Google App Script add-ons on Google Workspace Marketplace

Recently delving into Google App Script, I've taken my first steps in coding within the platform. Utilizing the deploy option provided by Google App Script, I successfully launched my app. However, upon deployment, I encountered difficulty locating my ...

The visibility of content that flickers on the webpage should be hidden with the display: none property during loading

Currently working on a new toy website, but encountering some unexpected behavior. On the homepage HTML file, there are two separate sets of <body> tags: <body class = "intro">...</body> <body class = "home">...</body& ...

issues with updating a MongoDB collection

One challenge I'm facing with my social media app is that I have two separate collections - one for users and the other for user posts. When I update information in a user's collection, it should also reflect in the corresponding posts (as the po ...

Choose various random values from columns in a two-dimensional array

Looking to randomly select 5 IDs from an array of rows. Below is the array named $test: $test = [ ['id' => 13, 'pets' => 8], ['id' => 15, 'pets' => 8], ['id' => 16, 'pets&apo ...

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...

Oops, it seems like there is a TypeError with the function window.initMap in Google Maps

For the past week, I have been struggling to update my marks on Google Maps while using AJAX in an HTML page. My controller fetches data from the database and sends it back, but now I am encountering the following error: TypeError: window.initMap is not a ...

React array mapping issue does not produce any error message

I have exhaustively searched through every answer on Stack Overflow in hopes of finding a solution to my problem. However, I find myself at an impasse as there are no error messages appearing in the console. It seems that there is a hidden bug eluding my d ...